我正在线上快速指南,开始在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
我确定它纯粹是我的错误然而可以改变什么才能使其正常运行?
答案 0 :(得分:3)
移动
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()