简体   繁体   English

为什么tkinter window中没有出现按钮?

[英]Why do the buttons not appear in the tkinter window?

I am currently trying to learn tkinter.我目前正在尝试学习 tkinter。 I do not understand why the buttons I defined do not appear in this code:我不明白为什么我定义的按钮没有出现在这段代码中:

from tkinter import *

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



            button1 = Button(self, text="Exit", width=12, command=self.clickButton1)

            button1.grid(row=0)

            button2 = Button(self, text="Test", width=12, command=self.clickButton2)

            button2.grid(row=1)

        def clickButton1(self):
            exit()

        def clickButton2(self):
            print("Nice")

root = Tk()
app = Window(root)
root.title("Tkinter window")

root.mainloop()

When I don't use a class it works.当我不使用 class 时,它可以工作。 Like this for example:像这样的例子:

from tkinter import *

root = Tk()

button1 = Button(root, text="Works!!!")
button1.grid(row=0)

button2 = Button(root, text="Also works!!!")
button2.grid(row=1)

root.mainloop()
´´´

The reason is that the class creates a frame, and then puts widgets inside the frame.原因是 class 创建了一个框架,然后将小部件放入框架内。 However, you never add the frame to the window so the widgets inside the frame will be invisible.但是,您永远不会将框架添加到 window,因此框架内的小部件将不可见。

You need to make sure and call pack , grid , or place on the instance of Window , just like you do with any other widget.您需要确保并在Window的实例上调用packgridplace ,就像处理任何其他小部件一样。

app = Window(root)
app.pack(fill="both", expand=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM