Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to be able to select a button based on what row and column it is in on a grid and the button and control its Text and Relief. I haven't been able to find anything on widgets or cells used in this manner. Edit: I changed where root is placed and now it says that I can't use a tuple that I recieved for 'relief' which makes sense, I need to access the widget itself. Any reccomendations

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 = {}
Row = {}'.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 = {}
Row = {}'.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.bind("<Button-3>",
                    lambda event, arg=x, brg=y: push(event, self, arg, brg))
                button['relief'] = 'raised'
                button.bind("<Button-1>",
                    lambda event, arg=x, brg=y: sunken(event, self, arg, brg))


                #button['command'] = sunken
                row.append(button)
             self.__buttons.append(row)



root = tkinter.Tk()
if __name__ == '__main__':
    MineSweep.main(int(width), int(height))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have a few things wrong with your program. First, sunken should be a method on the class. It's very weird to have it outside the class, and then you pass in self as some other argument. It works, but it makes the code very confusing.

That being said, you're actually very close to making this work. You're already saving a reference to each button in a list of lists, so you should be able to get the widget with self.__buttons[y][x]. However, because sunken is not part of the class, and because you named the variable with two underscores, the variable is not accessible to the sunken function.

If you change the variable to have a single underscore instead of a double, your code should work more-or-less exactly as it is (once you fix the syntax and indentation errors). The other solution is to make sunken a method on the class and fix how you call it (remove the self argument, call it as self.sunken), it will work with two underscores.

Frankly, using two underscores has zero practical benefit. Avoid the temptation to use it. At the very least, don't use it until you have your basic logic working, then you can go back and hide attributes you don't want to be exposed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...