Tkinter在菜单栏上添加多个按钮时的错误

问题描述 投票:0回答:1

试图创建一个菜单框,但我在添加多个按钮时遇到了问题,运行代码时只能看到一个 "退出 "按钮,请协助xx。

class Menu(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)

        self.master = master 

        self.init_menu()

    def init_menu(self):
        self.master.title("DUNGEON MENU")

        self.pack(expand = True, fill=BOTH)
        quitB = Button(self, text = "Quit", fg = "red", command = self.client_exit)
        quitB.grid(row = 0, column = 3, padx = 120)
    def client_exit(self):
        exit()


        lootB = Button(self, text = "Loot", command = None)
        lootB.grid(row = 1, column = 3, padx = 120)


root = Tk()
root.geometry("300x300")
app = Menu(root)
root.mainloop()
button.pack()```
python button tkinter
1个回答
0
投票

我已经根据你的代码创建了一个工作版本。你可以在下面的代码中找到我的发现作为注释。

我不太清楚你对你的代码有什么期望。现在 "Quit "和 "Loot "按钮在Frame上是可见的,如果你点击 "Quit "按钮,程序就会结束(Loot按钮没有任何作用)。

程式碼

from tkinter import Frame, BOTH, Button, Tk


class Menu(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.master = master

        self.init_menu()
        # You have to call the "client_exit" method to rendering the "Loot" button to Frame.
        self.client_exit()

    def init_menu(self):
        self.master.title("DUNGEON MENU")

        self.pack(expand=True, fill=BOTH)
        # Destroy the master if you click to the "Quit" button.
        quitB = Button(self, text="Quit", fg="red", command=lambda: self.master.destroy())
        quitB.grid(row=0, column=0, padx=120)

    def client_exit(self):
        # exit() # This exit is not needed because it breaks the program running.
        # You can define the call-back of button in "command" parameter of Button object.
        lootB = Button(self, text="Loot", command=None)
        lootB.grid(row=1, column=0, padx=120)


root = Tk()
root.geometry("300x300")
app = Menu(root)
root.mainloop()
# button.pack() # It does not have effect. You cannot define widgets after "mainloop"

输出:

>>> python3 test.py 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.