建立一个有按钮的棋盘,它总是一个正方形

2024-06-16 15:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个由按钮组成的棋盘。 我在一行中创建了3个小部件。外面有标签(填充),里面我想放一个棋盘。 我希望它始终占据屏幕宽度的90%,并自动调整其高度,使其始终保持正方形。这也将是必要的设置按钮总是正方形,但我也不能处理它。你能帮我吗

class ChessBoard(GridLayout):
    def __init__(self, **kwargs):
        super(ChessBoard, self).__init__(**kwargs)
        self.cols = 8

        for i in range(64):
            self.cell = Button(text="", size_hint_y=self.height/8, height=self.width/8)
            self.add_widget(self.cell)

class ChessBoardContainer(GridLayout):
    def __init__(self, **kwargs):
        super(ChessBoardContainer, self).__init__(**kwargs)

        self.orientation='horizontal'
        self.cols=3

        self.lab1 = Label(text="1")
        self.add_widget(self.lab1)

        self.board = ChessBoard()
        self.add_widget(self.board)

        self.lab2 = Label(text="2")
        self.add_widget(self.lab2)


class CombWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(CombWidget, self).__init__(**kwargs)
        self.orientation='vertical'

        self.but1 = Button(text="But1", font_size=40)
        self.add_widget(self.but1)

        self.chessb = ChessBoardContainer()
        self.add_widget(self.chessb)

        self.but2 = Button(text="But2", font_size=40)
        self.add_widget(self.but2)


class MyPaintApp(App):
    def build(self):
        return CombWidget()

现在这是我的结果:

enter image description here

我想要这样的东西(画师;))。也许没有这个标签也能做到

enter image description here


Tags: textselfaddsizeinitdefbuttonwidget
2条回答

这段代码生成的按钮在我看来相当方正。如果您计划使用图像作为棋子,按钮将符合这些图像的大小

from tkinter import Tk, Button

window = Tk ()
squares = []
index = 0
for x in range (8) :
    for y in range (8) :
        squares.append (Button (window, width = 7, height = 4))
        squares [index].grid (row = x, column = y)
        index += 1
window.mainloop ()

要使按钮成为正方形,您只需设置GridLayout单元格的高度和宽度,并尝试使用size_提示进行设置。试试这个:

from kivy.core.window import Window

class ChessBoard(GridLayout):
    def __init__(self, **kwargs):
        super(ChessBoard, self).__init__(**kwargs)
        self.cols = 8
        winsize = Window.size
        sizedict = {}

        # to set width and height of GridLayout cells, you should make a dict, where the key is col's/row's number and the value is size
        for i in range(self.cols):
            sizedict[i] = winsize[0]/8 #or you can divide it by 10 for example to have some black filling on the sides

        # and then simply do this
        self.cols_minimum = sizedict
        self.rows_minimum = sizedict

相关问题 更多 >