【问题标题】:Label and buttons overlapping when using different classes, tkinter使用不同类时标签和按钮重叠,tkinter
【发布时间】:2014-01-03 16:56:23
【问题描述】:

我正在使用 Python 开发一款扫雷游戏,但在使用 Tkinter 创建图形时遇到了问题。

扫雷数组由通过不同类创建的按钮组成。我使用 grid() 将它们放在窗口中。但是,当我想在窗口中放置其他项目(例如检查按钮和标签)时,它们似乎不适用于按钮数组。我试图让按钮位于窗口的左上角,而标签就在它们的右侧。但是当我尝试将它放在网格中时,无论我指定哪一行或哪一列,它都会出现在窗口的左上角。

当我在放置按钮的同一类中创建按钮时,我没有遇到此问题,但出于其他原因,我最好将它们放在不同的类中。

这是我正在尝试做的简化版本:

from tkinter import *

class Square(Frame):
    def __init__(self):
        self.button=Button(text="  ")

class App(Frame):
    def __init__(self,master):
        super(App,self).__init__(master)
        self.grid()
        self.matrix=[[None for i in range(10)] for i in range(10)]
        for x in range(10):
            for y in range(10):
                self.matrix[x][y]=Square()
                self.matrix[x][y].button.grid(row=x,column=y)
        self.label=Label(self, text="Hello")
        self.label.grid(row=0, column=10)

root=Tk()
App(root)
root.mainloop()

【问题讨论】:

    标签: python user-interface grid tkinter overlap


    【解决方案1】:

    问题的根源是矩阵中的小部件以根窗口为父级,而标签以内框为父级。您应该将self 传递给Square 类的构造函数(例如:self.matrix[x][y] = Square(self)) so that the buttons are children of theApp` 类。

    就个人而言,我认为更好的设计是将按钮矩阵放在它自己的框架内,与其他控件分开。我会创建一个 Grid 类,它是一个框架和按钮,仅此而已。然后,你的主程序变成这样:

    class App(Frame):
        def __init__(self, master):
            self.matrix = Grid(self, 10, 10)
            self.label = Label(self, text="Hello")
            self.matrix.grid(row=0, column=0, sticky="nsew")
    
            self.label.grid(row=0, column=1, sticky="nsew")
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(0, weight=1)
    

    【讨论】:

    • 谢谢你编程耶稣
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2023-03-21
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多