难以理解Python中的Tkinter主循环(mainloop)
好的,我现在有一个基本的窗口,上面有一个“编辑”和一个“查看”按钮。按照我现在的代码,点击这两个按钮都会显示一条消息:“这个按钮没用”。这两个按钮是我在“main_window”这个类里创建的。我还创建了另一个类叫“edit_window”,我希望在点击“编辑”按钮时能调用这个类。简单来说,点击“编辑”按钮应该会打开一个新窗口,里面有“添加”和“移除”这两个按钮。以下是我目前的代码……接下来我应该怎么做呢?
from Tkinter import *
#import the Tkinter module and it's methods
#create a class for our program
class main_window:
def __init__(self, master):
frame = Frame(master)
frame.pack(padx=15,pady=100)
self.edit = Button(frame, text="EDIT", command=self.edit)
self.edit.pack(side=LEFT, padx=10, pady=10)
self.view = Button(frame, text="VIEW", command=self.view)
self.view.pack(side=RIGHT, padx=10, pady=10)
def edit(self):
print "this button is useless"
def view(self):
print "this button is useless"
class edit_window:
def __init__(self, master):
frame = Frame(master)
frame.pack(padx=15, pady=100)
self.add = Button(frame, text="ADD", command=self.add)
self.add.pack()
self.remove = Button(frame, text="REMOVE", command=self.remove)
self.remove.pack()
def add(self):
print "this button is useless"
def remove(self):
print "this button is useless"
top = Tk()
top.geometry("500x500")
top.title('The Movie Machine')
#Code that defines the widgets
main = main_window(top)
#Then enter the main loop
top.mainloop()
1 个回答
0
只需创建一个 Toplevel
,而不是使用 Frame
:
class MainWindow:
#...
def edit(self):
EditWindow()
class EditWindow(Toplevel):
def __init__(self):
Toplevel.__init__(self)
self.add = Button(self, text="ADD", command=self.add)
self.remove = Button(self, text="REMOVE", command=self.remove)
self.add.pack()
self.remove.pack()
我根据大写字母命名法(CapWords convention)更改了类名(具体可以参考 PEP 8)。这不是强制的,但我建议你在所有Python项目中都使用这种命名方式,这样可以保持风格一致。