销毁窗口后不执行Tkinter代码

时间:2018-09-03 14:34:32

标签: python tkinter

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()

使用此代码,我基本上创建了掷骰子模拟器。在我的实际代码中,我给了turn()player1 / player2(这是类对象)函数,因此我可以跟踪它是谁。这就是为什么我会同时调用turn()2次的原因。

问题在于第一次turn()之后的代码不再执行(直到我手动关闭奇怪的根窗口为止)。据我所知,这应该起作用。

我打开了转弯功能,按下按钮后会打开diceAction功能。 diceAction()给我数字并杀死两个窗口。然后应该调用第二个turn(),过程继续进行,直到有人获胜(我没有在此代码中实现)。 也不执行print(“ Hi”)。我想念什么吗?您可以复制此代码并自己执行。

1 个答案:

答案 0 :(得分:0)

简短的回答是“无限循环和tkinter不能很好地玩”。长答案是,您永远不会逃脱window.mainloop()。我看不出有足够好的理由,您需要运行window.mainloop()result.mainloop()来证明tkinter中多个循环的麻烦。

主观上的一种更好的实现方法是让第一个turn()的结尾触发下一个的开始:

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