繁体   English   中英

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

[英]PyCharm Freezes When Clicking the Button - 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()

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

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

给这篇文章读一读 ,以了解为什么不应该在Tkinter应用程序中使用while循环。

另外,我认为这与您的实际代码不同,因为def GuessGame():块中的所有内容都无法使用缩进。

您会遇到无尽的while循环。 您应该删除while循环,并在guessedNumber == luckkynumber退出程序。 这样的事情应该工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM