【问题标题】:Creating a button to change menu创建一个按钮来改变菜单
【发布时间】:2014-11-15 17:33:29
【问题描述】:

我尝试使用 Python3 中的类创建一个简单的菜单。我已经尝试使用“其他菜单”按钮创建一个初始菜单,然后单击它会将我带到另一个带有“这是另一个菜单”按钮的菜单。

但它目前只在启动时显示两个菜单。

最终我想要一个包含 12 个按钮的初始菜单,然后重定向到其他菜单。我可以通过创建一个新窗口来做到这一点,但我更愿意将其保留在同一个窗口中。

我在下面做错了什么?

#import the tkinter module
from tkinter import *

#create a new class
class Try(Frame):
    def __init__(self, master):
        super(Try, self).__init__(master)
        self.grid(row = 2, sticky = W+E+N+S)
        #,padx=300
        self.create_widgets()

    def create_widgets(self):

        #create buttons
        self.bttn1 = Button(self, text = 'Other Menu')
        self.bttn1['command'] = self.create_widgets2()
        self.bttn1.grid(sticky = W+E+N+S) 

    def create_widgets2(self):

        #create buttons
        self.bttn2 = Button(self, text = 'This is the other menu')
        self.bttn2.grid(sticky = W+E+N+S) 

#main
root = Tk()
root.title('Editor')
root.geometry()
root.configure(background='black')

app = Try(root)

root.mainloop()

【问题讨论】:

    标签: python class python-3.x tkinter


    【解决方案1】:

    当您分配按钮的command 选项时,您在create_widgets 方法中调用create_widgets2 方法:

    self.bttn1['command'] = self.create_widgets2()
    #                                           ^^
    

    您需要删除括号,以便将command 选项分配给函数对象:

    self.bttn1['command'] = self.create_widgets2
    

    【讨论】:

    • 谢谢。它现在只显示初始菜单,但在单击时会不断添加另一个按钮。如何替换“其他菜单”按钮?
    • 您可以在create_widgets2 中调用self.bttn1.grid_forget() 以从窗口中删除旧按钮。要销毁其对象,请调用self.bttn1.destroy()。
    • self.bttn2 = Button(self, text = 'This is the other menu') self.bttn2.grid(sticky = W+E+N+S) self.bttn1.grid_forget() 这将返回self.bttn1.grid_forget() ^ TabError: inconsistent use of tabs and spaces in indentation
    • 这不是来自 Tkinter。您正在源文件中混合制表符和空格。永远不要这样做。您需要选择一个并始终如一地使用它..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多