【问题标题】:Difficulty understand Tkinter mainloop() in python难以理解python中的Tkinter mainloop()
【发布时间】:2013-03-05 23:29:57
【问题描述】:

好的,我有一个带有 EDIT 和 VIEW 按钮的基本窗口。正如我的代码所代表的那样, EDIT 和 VIEW 都返回一条消息“这个按钮没用”。我在“main_window”类下创建了这些。我创建了另一个类“edit_window”,希望在单击 EDIT 按钮时调用它。本质上,单击编辑按钮应更改显示带有按钮添加和删除的新窗口。到目前为止,这是我的代码......下一个合乎逻辑的步骤是什么?

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()

【问题讨论】:

  • 你对 mainloop 有什么不了解的地方?对我来说,您似乎正在寻找Toplevel,您可以使用它使edit_window 成为一个单独的窗口。
  • 我可能解释得不够清楚。我希望主窗口根据您单击的按钮进行更新。因此,如果单击 EDIT,我不想打开新窗口,我希望现有窗口完全显示 EDIT 和 VIEW --- 它应该更新以显示 ADD REMOVE,其方式与之前显示 EDIT VIEW 的方式相同。说得通?所以我假设 Toplevel 会简单地用 ADD REMOVE 打开一个新窗口。

标签: python python-2.7 tkinter


【解决方案1】:

只需创建一个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 约定更改了类名(请参阅PEP 8)。这不是强制性的,但我建议您在所有 Python 项目中使用它以保持统一的样式。

【讨论】:

  • 欣赏答案!不过,我试图让程序在单个窗口中运行。顶层窗口很烦人。有没有办法在删除按钮编辑视图时添加按钮添加删除?要更新窗口,可以这么说吗?
  • 更新:我意识到我可以隐藏根窗口和 force_focus 顶层窗口,所以看起来窗口不会改变。感谢您的帮助!
猜你喜欢
  • 2015-05-23
  • 1970-01-01
  • 2020-08-30
  • 2016-08-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 2016-12-29
相关资源
最近更新 更多