当单击Python/Tkin按钮时,PyCharm将冻结

2024-09-28 03:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始用python的Tkinter模块开发一个简单的应用程序。但我的按钮在屏幕上不太复杂。下面是我的代码

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

Tags: textyouhavecolumnwindowlabelgridrow
2条回答

你有一个无尽的while循环。 您应该删除while循环并退出程序if 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()

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

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

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

另外,我认为这与实际的代码并不相同,因为您的缩进对于def GuessGame():块中的所有内容都是关闭的。在

相关问题 更多 >

    热门问题