from tkinter import *
from random import *
root = Tk()
#A function to create the turn for the current player. The current player isnt in this code as it is not important
def turn():
window = Toplevel()
dice = Button(window, text="Roll the dice!", bg= "white", command=lambda:diceAction(window))
dice.pack()
window.mainloop()
#a function to simulate a dice. It kills the function turn.
def diceAction(window):
result = Toplevel()
y = randint(1, 6)
# i do something with this number
quitButton = Button(result, text="Ok!", bg="white", command=lambda: [result.destroy(), window.destroy()])
quitButton.pack()
window.destroy()
result.mainloop()
#A function to create the playing field and to start the game
def main():
label1 = Button(root, text="hi", bg="black")
label1.pack()
while 1:
turn()
print("Hi")
turn()
main()
root.mainloop()
有了这个代码,我基本上创建了一个掷骰子模拟器。在我的实际代码中,我给出了函数师()player1/player2(这是类对象),这样我就可以跟踪轮到谁了。这就是为什么我打电话2次在同时。
问题是,第一次turn()之后的代码不再执行(直到我手动关闭根窗口,这很奇怪)。据我所知,这应该行得通。
我打开旋转功能,按下按钮后打开骰子动作功能。diceAction()给出了数字并杀死了两个窗口。然后调用second turn(),该过程将继续,直到有人获胜(我在这段代码中没有实现)。打印(“Hi”)也不会执行。我错过什么了吗?您可以复制此代码并自己执行。
简单的回答是“无限循环和tkinter
不能很好地结合在一起”。很长的答案是,你永远不会逃脱窗口。mainloop()
。我看不出你需要窗口的充分理由。mainloop()
和结果。mainloop()。
一个主观上更好的方法是让第一个的结束()
触发下一个的开始:
from tkinter import *
from random import *
root = Tk()
global turnCount
turnCount = 0
def turn():
window = Toplevel()
dice = Button(window, text="Roll the dice!", bg="white", command=lambda:diceAction())
dice.pack()
def diceAction():
result = Toplevel()
y = randint(1, 6)
quitButton = Button(result, text="Ok!", bg="white", command=lambda: nextTurn())
quitButton.pack()
def nextTurn():
global turnCount
turnCount = turnCount + 1
for i in root.winfo_children():
if str(type(i)) == "<class 'tkinter.Toplevel'>":
i.destroy()
turn()
def main():
label1 = Button(root, text="hi", bg="black")
label1.pack()
turn()
main()
root.mainloop()
我建议尝试在这样的项目上使用OOP,而不是我上面声明的global
。