简体   繁体   中英

Why tkinter-buttons do all disable?

I am following a beginner's Python guide book and I am stuck with one particular task with tkinter. I've followed the code from the book but it still does not seem to work properly:

The purpose is to make a guessing game where buttons are pressed two times. If the user finds two same symbols after guessing two times in a row, those buttons/symbols are disabled and stay visible. In other case, they are hidden and guessing starts again. Problem is: After pressing the buttons they all stay visible. Please see attachment. Screenshot of outcome

For doing this code I am using Jupyter Notebook 5.5.0 which has worked well with other exercises in the book. I was wondering if it is about the notebook (also the graphics look different here than in the book) I am using or just a bug in the code?

Thanks in advance!

import random
import time
from tkinter import Tk, Button, DISABLED 

def show_symbol(x, y): 

    global first 
    global previousX, previousY
    buttons[x, y]["text"] = button_symbols[x, y] 
    buttons[x, y].update_idletasks() 

    if first: 

        previousX = x 
        previousY = y
        first = False 

    elif previousX != x or previousY != y: 

        if buttons[previousX, previousY]["text"] != buttons[previousX, previousY]["text"]: 

            time.sleep(0.5) 
            buttons[previousX, previousY]["text"] = ""
            buttons[x, y]["text"] = ""

        else: 

            buttons[previousX, previousY]["command"] = DISABLED
            buttons[x, y]["command"] = DISABLED 

        first = True 

root = Tk()
root.title("Find a pair")
root.geometry("500x500") 
root.resizable(width=False, height=False) 

buttons = {}
first = True
previousX = 0 
previousY = 0 

button_symbols = {}
symbols = [u"\u2702", u"\u2702", u"\u2705", u"\u2705", u"\u2708", u"\u2708", u"\u2709", u"\u2709", u"\u270A", u"\u270A",
          u"\u270B", u"\u270B", u"\u270C", u"\u270C", u"\u270F", u"\u270F", u"\u2712", u"\u2712", u"\u2714", u"\u2714",
          u"\u2716", u"\u2716", u"\u2728", u"\u2728"]

random.shuffle(symbols)

for x in range(6): 

    for y in range(4):

        button = Button(command=lambda x=x, y=y: show_symbol(x, y), width=3, height=3)
        button.grid(column=x, row=y) 
        buttons[x, y] = button 
        button_symbols[x, y] = symbols.pop() 

root.mainloop()

The following if statement will always return false because it is checking if itself is not equal to itself . A simple oversight ;)

if buttons[previousX, previousY]["text"] != buttons[previousX, previousY]["text"]: 

Just change it to the following:

if buttons[previousX, previousY]["text"] != buttons[x, y]["text"]: 

I tested your code and it works with that change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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