小部件不会出现在简单的tkinter应用程序中

时间:2017-03-06 15:47:30

标签: python layout tkinter

我看了一个类似标题的其他问题并且已经阅读了答案,但是没有任何对我有用。我正在尝试使用列表框+滚动条创建一个简单的应用程序,其下方有两个按钮,所有这些都在一个组框中。我用过pyqt,但这是我第一次使用tkinter:

import tkinter as tk


class InputWindow(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.initialize()

    def initialize(self):
        # Group box to contain the widgets
        self.input = tk.LabelFrame(self, text="Input Files")

        # Listbox with scrollbar to the side
        self.listbox = tk.Listbox(self.input)
        self.scrollbar = tk.Scrollbar(self.listbox, orient=tk.VERTICAL)
        self.listbox.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox.yview)
        self.listbox.grid(row=0, column=0, columnspan=2)

        self.add_btn = tk.Button(self.input, text="Add...")
        self.add_btn.grid(row=1, column=0)

        self.remove_btn = tk.Button(self.input, text="Remove")
        self.remove_btn.grid(row=1, column=1)


if __name__ == "__main__":

    root = tk.Tk()
    app = InputWindow(root)
    root.mainloop()

这或多或少是我想要的,但在tkinter中:

enter image description here

我做错了什么/如何做到这一点?

1 个答案:

答案 0 :(得分:2)

你忘记了两件事:

  1. 打包(或网格或放置)app
  2. 打包(或网格或放置)input
  3. 您使用所需的声明进行编程:

    import tkinter as tk
    
    
    class InputWindow(tk.Frame):
    
        def __init__(self, parent, *args, **kwargs):
            tk.Frame.__init__(self, parent, *args, **kwargs)
            self.parent = parent
            self.initialize()
    
        def initialize(self):
            # Group box to contain the widgets
            self.input = tk.LabelFrame(self, text="Input Files")
    
            # Listbox with scrollbar to the side
            self.listbox = tk.Listbox(self.input)
            self.scrollbar = tk.Scrollbar(self.listbox, orient=tk.VERTICAL)
            self.listbox.config(yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.listbox.yview)
            self.listbox.grid(row=0, column=0, columnspan=2)
    
            self.add_btn = tk.Button(self.input, text="Add...")
            self.add_btn.grid(row=1, column=0)
    
            self.remove_btn = tk.Button(self.input, text="Remove")
            self.remove_btn.grid(row=1, column=1)
    
            self.input.pack(expand=1, fill="both") # Do not forget to pack!
    
    if __name__ == "__main__":
    
        root = tk.Tk()
        app = InputWindow(root)
        app.pack(expand=1, fill="both")  # packing!
        root.mainloop()