单击按钮时PyCharm冻结--Python / Tkinter

时间:2017-12-21 11:29:58

标签: python tkinter

我开始使用python的Tkinter模块开发一个简单的应用程序。我的代码不是很复杂但是当我点击屏幕上的按钮时,Pycharm冻结了。这是我的代码,

from random import *
from tkinter import *

window=Tk()

luckynumber=randint(0,50)

def GuessGame():
guessedNumber=int(guessdigit.get())
while True:
    if guessedNumber == luckynumber:
        cx2=Label(window,text="Congrats!",font=("Fixedsys",20))
        cx2.grid(row=3,column=0)
        break
    elif guessedNumber < luckynumber:
        cx2 =Label(window, text="You have to guess more than that!", font=
("Fixedsys", 20))
        cx2.grid(row=3, column=0)
    elif guessedNumber > luckynumber:
        cx2 =Label(window, text="You have to guess less than that!", font=
("Fixedsys", 20))
        cx2.grid(row=3, column=0)



cx1=Label(window,text="You have to guess the number!",font=("Fixedsys",20))
cx1.grid(row=0,column=0)
guessdigit=Entry(window,font=("Fixedsys",20))
guessdigit.grid(row=1,column=0)
cx3=Button(window,text="To submit your guess, click it!",font=
("Fixedsys",20),command=GuessGame)
cx3.grid(row=2,column=0)

window=mainloop()

2 个答案:

答案 0 :(得分:1)

您在tkinter代码中使用了while循环。

当你使用Tkinter时,你不能使用任何while循环,因为这基本上会抛出Tkinter。

Give this post a read,了解为什么你不应该在Tkinter应用程序中使用while循环。

此外,我认为这与您的实际代码不同,因为def GuessGame():块内的所有内容的缩进都已关闭。

答案 1 :(得分:0)

你有一个无尽的循环。 如果guessedNumber == luckkynumber,您应该删除while循环并退出程序。 这样的事情应该有效:

from random import *
from tkinter import *

window=Tk()

luckynumber=randint(0,50)

def GuessGame():
   guessedNumber=int(guessdigit.get())
   # NO while loop: this function will execute each time the user press the button
   if guessedNumber == luckynumber:
      cx2=Label(window,text="Congrats!",font=("Fixedsys",20))
      cx2.grid(row=3,column=0)
      window.quit() # Quit your window if user guess the number
   elif guessedNumber < luckynumber:
      cx2 =Label(window, text="You have to guess more than that!", font=
("Fixedsys", 20))
      cx2.grid(row=3, column=0)
   elif guessedNumber > luckynumber:
      cx2 =Label(window, text="You have to guess less than that!", font=
("Fixedsys", 20))
      cx2.grid(row=3, column=0)



cx1=Label(window,text="You have to guess the number!",font=("Fixedsys",20))
cx1.grid(row=0,column=0)
guessdigit=Entry(window,font=("Fixedsys",20))
guessdigit.grid(row=1,column=0)
cx3=Button(window,text="To submit your guess, click it!",font=
("Fixedsys",20),command=GuessGame)
cx3.grid(row=2,column=0)

window=mainloop()