Tkinter, py - 创建一个游戏,每次单击一个按钮都会出现一个新按钮

问题描述 投票:0回答:1

我想从

Button1
开始,您单击
Button1
并创建
Button2
,您单击
Button1
Button2
并创建
Button3
,依此类推,直到您单击正确的按钮(当前按钮将是一个随机按钮编号)

这是我到目前为止所拥有的,但所有这些都创建了一个名为

Button1

的新按钮
from tkinter import *
import random

root = Tk()
root.geometry("1000x1000")

def add_button():
     start_button.pack_forget()
     count = 0
     count = count + 1
     text_button = "Button%s"%(count)
     i = Button(root, text=text_button,command = add_button)
     i.place(x=random.randint(350, 600), y=random.randint(400, 600))

var=StringVar()
banner = Message(root, textvariable=var, relief=RIDGE)
var.set("Click a button\nThe more buttons you click, the more buttons get     added.\nClick the correct button to win!")
banner.pack()
start_button = Button(root, text='Start Game',command = add_button)
start_button.pack()

root.mainloop()

#create multiple buttons after start button is selected
#tell player the number to win changes every time
#add a timner
#add for i in number of buttons  to choice a random button number that wins
#add a win screen
#have it show time
#add a quit game button at bottom
python tkinter button
1个回答
0
投票

每次调用

count
时,您都在重新定义
add_button()
变量,这意味着每次调用此函数时,计数都会回到零。要解决此问题,只需在函数外部定义变量,因此将
add_button()
函数替换为此:

count = 0
def add_button():
     start_button.pack_forget()
     count = count + 1
     text_button = "Button%s"%(count)
     i = Button(root, text=text_button,command = add_button)
     i.place(x=random.randint(350, 600), y=random.randint(400, 600))

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.