用tkinter调用函数的问题

时间:2018-09-02 15:20:57

标签: 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 = Tk()  
    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 = Tk()
    y = randint(1, 6)
    quitButton = Button(result, text="Ok!", bg="white", command=result.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()之后while函数中的代码直到我关闭根窗口(因为它代表了运动场,所以我不想要)后才执行。您可以复制此代码,并根据需要自己执行。

我不知道是什么原因造成的,还没有在网上找到任何东西。抱歉,很长的代码,但我写了它,以便它可以执行。

1 个答案:

答案 0 :(得分:0)

我不知道为什么会发生此特定问题,但是您的代码中有几件事被认为是不好的做法。 而不是创建Tk()的多个实例,而应该对所需的任何弹出窗口使用顶级小部件。另外,最好使用root.mainloop()运行程序,而不要使用while循环。

我已经对您的代码进行了一些编辑,以使其使用Toplevel小部件并丢弃while循环。

from tkinter import *
from random import *


#A function to create the turn for the current player. The current player isnt in this code as it is not important
def turn(prev=None):
    # destroy the previous turn
    if prev:
        prev.destroy()

    # pop up with dice
    window = Toplevel()  
    dice = Button(window, text="Roll the dice!", bg= "white")
    dice.config(command=lambda b=dice, w=window:diceAction(b, w))
    dice.pack()


#a function to simulate a dice, reconfigures the pop-up
def diceAction(button, window):
    # roll dice
    y = randint(1, 6)
    # use dice result here?
    print(y)

    # reconfigure button, the command now starts a new turn
    button.config(text='ok', command=lambda w=window:turn(prev=w))




root = Tk()

# I hijacked this button to use as a start button
label1 = Button(root, text="hi", bg="black", command=turn)
label1.pack()

root.mainloop()

我不知道这是否是您所需要的,但是它可以用作问题代码是否有效。 抱歉,我无法解决错误原因。