Я сделал версию, которая использует кнопку только для проверки один раз - без цикла while
, который останавливает mainloop()
и tkinter не может работать правильно.После того, как вы введете char в запись, вы должны нажать кнопку, он проверяет этот char (и другие переменные) и завершает работу, чтобы mainloop()
мог запустить его снова и мог ждать, когда вы нажмете кнопку в следующий раз.
Я использую global
, чтобы сохранить значения вне функции, чтобы они не были удалены между двумя исполнениями.
Я не устанавливаю sword
и другие значения при запуске, но в reset()
, поэтому я могу запустить его много раз, чтобы установить новый sword
перед следующей игрой.
Я добавил несколько пробелов и пустых строк, чтобы сделать код более читабельным.
import tkinter as tk
import random
wlist = "monday friday sunday blue orange red brown ".split()
def reset():
'''reset values before first and next game'''
global turns
global guesses
global sword
turns = 5
guesses = ""
sword = random.choice(wlist)
def check():
''' check only once when button is pressed'''
global turns
global guesses
global sword
# get value from entry
guess = ent.get()
guesses += guess
# check new char in sword to display '-'
failed = 0
lb1["text"] = ''
for char in sword:
if char in guesses:
lb1["text"] += char
else:
lb1["text"] += "-"
failed += 1
# check result
if failed == 0:
lb1["text"] = "you won"
# end of game - set variables before next game
reset()
# display after reset because it needs value in `sword`
lb2["text"] = "Days of the week\n and some colors.... " + sword
else:
if guess not in sword:
turns -= 1
lb2["text"] = "you are wrong"
else:
lb2["text"] = "good choice"
if turns == 0:
lb2["text"] = "Game is over.\nThe answer was {0}".format(sword)
# end of game - set variables before next game
reset()
# display after reset because it needs value in `sword`
lb2["text"] = "Days of the week\n and some colors.... " + sword
# clear entry before next char
ent.delete(0,'end')
# --- main ---
wn = tk.Tk()
wn.geometry("400x300+10+10")
wn.config(bg="silver")
but1 = tk.Button(wn, text="Check char", command=check)
but1.place(x=20, y=95)
ent = tk.Entry(wn, width=12)
ent.place(x=10, y=70)
lb1 = tk.Label(bg="pink", width=10)
lb1.place(x=10, y=10)
lb2 = tk.Label(bg="yellow", width=28)
lb2.place(x=110, y=5)
# set variables before first game
reset()
# display after reset because it needs value in `sword`
lb2["text"] = "Days of the week\n and some colors.... " + sword
wn.mainloop()