Tkinter Grid: How to position widgets so they are not stuck together

后端 未结 5 1071
不知归路
不知归路 2020-12-02 09:07

I\'m trying to create two Label widgets that are in the top left and top right corners of my test UI. The problem is that the widgets are stuck together and I\'d like there

5条回答
  •  执念已碎
    2020-12-02 09:34

    Better late than never ;)

    Tkinter's "grid" wants to put everything together. Thats why you are not able to skip cells. You have to specify the widths and then anchor the text. I added color to help show cells. I put the bd in the frame. Then I had to give width to the cells left and right so grid would give weight to them. Then anchor text West or East. Im not sure why I had to add extra 2 spaces for each cell but I figured it was a font issue.

    I believe Rodas is cleaner and simpler but I tried to stay within the parameters you asking about.

    Pack is easier and faster for small stuff.

    from tkinter import *
    
    class MyApp:
        def __init__(self, parent):
            self.myParent = parent
    
            self.main_container = Frame(parent, bg="green")
            self.main_container.grid()
    
            self.top_frame = Frame(self.main_container)
            self.top_frame.grid()
    
            self.top_left = Frame(self.top_frame, bd=2)
            self.top_left.grid(row=0, column=0)
    
            self.top_right = Frame(self.top_frame, bd=2)
            self.top_right.grid(row=0, column=2)
    
            self.top_left_label = Label(self.top_left, bd=2, bg="red", text="Top Left", width=22, anchor=W)
            self.top_left_label.grid(row=0, column=0)
    
            self.top_right_label = Label(self.top_right, bd=2, bg="blue", text="Top Right", width=22, anchor=E)
            self.top_right_label.grid(row=0, column=0)
    
            self.bottom_frame = Frame(self.main_container, bd=2)
            self.bottom_frame.grid(row=2, column=0)
    
            self.text_box = Text(self.bottom_frame, width=40, height=5)
            self.text_box.grid(row=0, column=0)
    
    root = Tk()
    root.title("Test UI")
    myapp = MyApp(root)
    root.mainloop()
    

提交回复
热议问题