I'm currently in a project of making "Shut The Door, Dice Game". I've used the for loop to label the "door", now my problem is how to take the "door" to update to "-" after click the correct "door".
import tkinter, random
window = tkinter.Tk(); window.title("Dice Game - Shut the DOOR")
def roll():
result["text"] = int(random.randint(1,6))
result_2["text"] = int(random.randint(1,6))
for door in range(12):
number = tkinter.Label(window, text=door 1)
number.grid(row=0, column=door, sticky="e")
result = tkinter.Label(text="-")
result_2= tkinter.Label(text="-")
result.grid(row=1, column=0)
result_2.grid(row=1,column=1, sticky="w")
dice = tkinter.Button(window, text="Roll", command=roll)
dice.grid(row=2, column=0)
Appreciate for the help
CodePudding user response:
Use .bind("<Button>", function)
to do something when a label (or any other widget) is clicked. First, define a function to handle the event, then add number.bind("<Button>", function_name)
to make the function run when number
is clicked.
Tkinter will automatically pass an argument to the function containing information about the event so the function must accept one argument. This is used to get which number was clicked.
Full code:
import tkinter, random
window = tkinter.Tk(); window.title("Dice Game - Shut the DOOR")
def change_text(event):
number = event.widget
if result["text"] == "-" or number["text"] == "-": return
if int(result["text"]) int(result_2["text"]) == int(number["text"]):
number["text"] = "-"
def roll():
result["text"] = int(random.randint(1,6))
result_2["text"] = int(random.randint(1,6))
for door in range(12):
number = tkinter.Label(window, text=door 1, width=1)
number.grid(row=0, column=door, sticky="e")
number.bind("<Button>", change_text)
result = tkinter.Label(text="-")
result_2= tkinter.Label(text="-")
result.grid(row=1, column=0)
result_2.grid(row=1,column=1, sticky="w")
dice = tkinter.Button(window, text="Roll", command=roll)
dice.grid(row=2, column=0)