繁体   English   中英

用按钮构建一个棋盘,它总是一个正方形

[英]Building a chessboard with buttons, which is always a square

我正在尝试构建一个由按钮组成的棋盘。 我在一行中创建了 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()

现在这是我的结果:

在此处输入图片说明

我想得到这样的东西(油漆大师;))。 也许没有这个标签可以做到?

在此处输入图片说明

要使按钮成为正方形,您只需设置 GridLayout 单元格的高度和宽度,并且您正在尝试使用 size_hint 来实现。 尝试这个:

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

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

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 ()

暂无
暂无

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

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