我正在尝试制作一个小型游戏,该游戏向您显示一个带有8个按钮的窗口,您选择一个即可获胜。接下来的7个按钮应该会错过。窗口弹出,但是没有按钮。任何想法代码有什么问题吗?
from tkinter import *
import random
t = Tk()
t.title("Select button")
t.geometry("300x350")
def insert_buttons():
count_buttons=8
global buttons
buttons = []
good = random.randint (0,count_buttons-1)
for i in range (count_buttons):
if i == good:
buttons.append(Button(t, text = "Select", command=hit))
else:
buttons.append(Button(t, text = "Select", command=miss))
for i in buttons:
i.pack (fill=BOTH, expand=YES)
def hit():
for i in buttons:
i.destroy()
global etykiet
etykiet = label(t, text = "BRAWO! It's a hit!")
etykiet.pack(fill=BOTH, expand=YES)
t.after(5000,restart)
def miss():
for i in buttons:
i.destroy()
global etykiet
etykieta = label(t, text - "Try again")
etykieta.pack(fill=BOTH, expand=YES)
t.after(5000, restart)
def restart():
etyket.destroy()
inserty_buttons()
答案 0 :(得分:0)
我修复了您的代码,它应该可以正常工作。有很多错误,请记住仔细阅读代码并检查文档。我也建议使用4个空格缩进
from tkinter import *
import random
t = Tk()
t.title("Select button")
t.geometry("300x350")
def insert_buttons():
count_buttons = 8
global buttons
buttons = []
good = random.randint(0, count_buttons - 1)
for i in range(count_buttons):
if i == good:
buttons.append(Button(t, text="Select", command=hit))
else:
buttons.append(Button(t, text="Select", command=miss))
for i in buttons:
i.pack(fill=BOTH, expand=YES)
def hit():
currentbuttons = globals()['buttons']
globals()['buttons'] = []
for i in currentbuttons:
i.destroy()
etykieta = Label(t, text="BRAVO! ITS A HIT")
etykieta.pack(fill=BOTH, expand=YES)
buttons.append(etykieta)
t.after(2000, restart)
def miss():
currentbuttons = globals()['buttons']
globals()['buttons'] = []
for i in currentbuttons:
i.destroy()
etykieta = Label(t, text="Try again")
etykieta.pack(fill=BOTH, expand=YES)
buttons.append(etykieta)
t.after(2000, restart)
def restart():
for button in globals()['buttons']:
button.destroy()
globals()['buttons'] = []
insert_buttons()
insert_buttons()
t.mainloop()