Python模块只在函数内部工作

gcuhipw9  于 2023-05-30  发布在  Python
关注(0)|答案(2)|浏览(186)
# program saved as wolgui.py
from tkinter import *
Window = Tk()
Window.title("WolframAlpha")
Window.geometry("540x590")

'''menu = Menu(Window)
item = Menu(menu)
item.add_command(label='New')
menu.add_cascade(label='Execute once more', menu=item)
Window.config(menu=menu)'''
lbl = Label(Window, text = "Ask WolframAlpha")
lbl.grid()
txt = Entry(Window, width=10)
txt.grid(column =1, row =0)


def click():
    resu =  Entry(Window,bd=5)
    #Window.mainloop()
    import wolframalpha
    client = wolframalpha.Client('YOUR_CLIENT_ID')
    result = client.query(resu)
    output = next(result.results).text
    

# button widget with blue color text inside
# Set Button.grid
btn = Button(Window, text = "Click me for the answer" ,fg = "blue",command=click)
btn.grid(column=2, row=0)

lbl2 = Label(Window, text = "Answer: ")
lbl2.grid()
txt2 = Entry(output, width=10)
txt2.grid(column =1, row =0)
lbl2.grid()

Window.mainloop()

为什么我得到这个traceback??

Traceback (most recent call last):
  File "wolgui.py", line 38, in <module>
    txt2 = Entry(output, width=10)
NameError: name 'output' is not defined

***Repl Closed***

我想我已经导入了这个函数-那么我应该重写/再次导入它吗??还是压痕问题?原谅我的无知-我在Python中不是太多产...

lqfhib0f

lqfhib0f1#

lbl2 = Label(Window, text = "Answer: ")
lbl2.grid()
txt2 = Entry(output, width=10)
txt2.grid(column =1, row =0)
lbl2.grid()

我想如果你把这个结构放在函数的底部,你的问题就解决了。问题是你在函数中定义的“output”变量将不会被定义,除非函数被执行。因为您在第一次运行时调用此变量,所以会遇到错误。

8oomwypt

8oomwypt2#

txt2 = Entry(output,width=10)
NameError:未定义名称“output”。
你有打字错误。
这个问题是可以解决的。
更改此:

txt2 = Entry(output, ...

txt2 = Entry(Window, ...

相关问题