我正在按照在线快速指南开始在 Python (2.7) 中使用 Tk,到目前为止,我有以下代码:
from Tkinter import *
root = Tk()
root.title("Note Taker")
root.mainloop()
button1 = Button(root, text="button1", command = Button1)
button2 = Button(root, text="button2", command = Button2)
button3 = Button(root, text="button3", command = Button3)
text = Entry(root)
listbox = Listbox(root)
text.pack()
button1.pack()
button2.pack()
button3.pack()
listbox.pack()
def Button1():
listbox.insert(END, "button1 pressed")
def Button2():
listbox.insert(END, "button2 pressed")
def Button3():
text_contents = text.get()
listbox.insert(END, text_contents)
text.delete(0,END)
但是,当我运行此命令时,GUI 已加载,但没有显示任何按钮,而是给出了此“NameError”:
button1 = Button(root, text="button1", command = Button1)
NameError: name 'Button1' is not defined
我确定这纯粹是我的错误,但是可以更改什么才能使其正确运行?
最佳答案
移动
def Button1():
listbox.insert(END, "button1 pressed")
之前
button1 = Button(root, text="button1", command=Button1)
因为 command = Button1
引用 Button1
。
当然,对 Button2
和 Button3
执行相同的操作。
同时移动
root.mainloop()
到脚本的底部,因此在定义 Tkinter 小部件之前,控制流不会陷入事件循环中。
from Tkinter import *
root = Tk()
root.title("Note Taker")
def Button1():
listbox.insert(END, "button1 pressed")
def Button2():
listbox.insert(END, "button2 pressed")
def Button3():
text_contents = text.get()
listbox.insert(END, text_contents)
text.delete(0, END)
button1 = Button(root, text="button1", command=Button1)
button2 = Button(root, text="button2", command=Button2)
button3 = Button(root, text="button3", command=Button3)
text = Entry(root)
listbox = Listbox(root)
text.pack()
button1.pack()
button2.pack()
button3.pack()
listbox.pack()
root.mainloop()
关于python-2.7 - 运行时 Tkinter 按钮 'not defined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934192/