Tkinter 使用行和列标识按钮

108 阅读2分钟

在Tkinter中, 我想要根据按钮在网格中的行和列来选择一个按钮并控制它的文本和relief属性。但我无法找到任何有关以这种方式使用部件或单元格的信息。

2、解决方案

可以使用grid_location()方法来获取按钮在网格中的行和列。然后可以使用这些信息来控制按钮的文本和relief属性。

def sunken(event, self, x, y):
    button = event.widget
    button['relief'] = 'sunken'
    if x - 1 < 0 :
        return
    if x > int(width) + 1 :
        return
    if y - 1 < 0 :
        return
    if y > int(height) + 1 :
        return

我们可以使用grid()方法来将按钮添加到网格中,并使用command()方法来指定当按钮被点击时要执行的函数。

    def __build_buttons(self):
        self.__buttons = []
        for y in range(self.__height):
            row = []
            for x in range(self.__width):
                button = tkinter.Button(self, state='disabled')
                button.grid(column=x, row=y)
                button['text'] = ' '
                button['command'] = functools.partial(self.__push, x, y)
                row.append(button)
            self.__buttons.append(row)


当按钮被点击时,push()函数将被调用,该函数将使用grid_location()方法来获取按钮在网格中的行和列,然后使用这些信息来控制按钮的文本和relief属性。

def push(event, self, x, y):
    button = event.widget
    if Matrix[x][y] == 1 :
         print('Column = {}\nRow = {}'.format(x, y))

完整代码:

import tkinter
import functools
import random
from time import sleep

width = input('Enter the grid width. ')
height = input('Enter the grid height. ')
numb = input('Enter the number of bombs. ')
Matrix = [[0 for lp in range(int(width))] for fg in range(int(height))]

def ranintx():
    return  random.randint(0,int(width))
def raninty():
    return random.randint(0,int(height))

def placemines():
   y = ranintx()
   x = raninty()
   for ranintformine in range(int(numb)):
       x = ranintx()
       y = raninty()
       Matrix[y-1][x-1] = 1

placemines()

def sunken(event, self, x, y):
    button = event.widget
    button['relief'] = 'sunken'
    if x - 1 < 0 :
        return
    if x > int(width) + 1 :
        return
    if y - 1 < 0 :
        return
    if y > int(height) + 1 :
        return
    if Matrix[x][y] == 1 :
        top = tkinter.Toplevel()
        top.title("About this application...")

        msg = tkinter.Message(top, text="You Lose")
        msg.pack()

        button = tkinter.Button(top, text="Dismiss", command=top.destroy)
        button.pack()
        print('Column = {}\nRow = {}'.format(x, y))
    else:
       n1 = x - 1
       n2 = y - 1

       for lp in range(3):
            for lp2 in range(3):
                abutton = root.grid_location(n1, n2)
                abutton['relief'] = ['sunken']
                # I want to be able to change and select the button here. This was one of my poor attempt
                n2 =+ 1
            n1 =+ 1

def push(event, self, x, y):
    button = event.widget
    if Matrix[x][y] == 1 :
         print('Column = {}\nRow = {}'.format(x, y))

class MineSweep(tkinter.Frame):

    @classmethod
    def main(cls, width, height):
        window = cls(root, width, height)
        '''placemine()'''
        root.mainloop()

    def __init__(self, master, width, height):
        super().__init__(master)
        self.__width = width
        self.__height = height
        self.__build_buttons()
        self.grid()
    #def sunken(event):
    #    button = event.widget
    #    button['relief'] = 'sunken'
    def __build_buttons(self):
        self.__buttons = []
        for y in range(self.__height):
            row = []
            for x in range(self.__width):
                button = tkinter.Button(self, state='disabled')
                button.grid(column=x, row=y)
                button['text'] = ' '
                print(grid.slaves)
                self.checked = True
                button['command'] = functools.partial(self.__push, x, y)
                button['relief'] = 'raised'
                row.append(button)
            self.__buttons.append(row)



root = tkinter.Tk()
if __name__ == '__main__':
    MineSweep.main(int(width), int(height))