[英]Conditions and while loop not working properly py(tkinter)
im making a Guess the number game but i have a problem:The user must guess a certain number, and if it exceeds that, the game ends and the user's status is determined,So I created a variable named sam and did this我正在做一个猜数字游戏但是我有一个问题:用户必须猜一个特定的数字,如果超过这个数字,游戏结束并且用户的状态被确定,所以我创建了一个名为 sam 的变量并做了这个
sam = 0
And then I made a loop with while and said:然后我用 while 做了一个循环并说:
while sam < 10:
And then, every wrong guess will be added to sam, but the problem is that if you do something wrong, this will happen:然后,每一次错误的猜测都会被添加到 sam 中,但问题是如果你做错了什么,就会发生这种情况:
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>you lose
That is, it repeats a condition until sam exceeds 10 And I don't know what to do, my code:也就是说,它会重复一个条件,直到 sam 超过 10 我不知道该怎么办,我的代码:
from tkinter import *
sam = 0
def get_1():
global correct
correct = int(player1.get())
player1.pack_forget()
sumbit.pack_forget()
def Guess():
global sam
a = int(player_2.get())
while sam < 10:
if a == correct:
break
elif a > correct:
print(a,"is higher")
sam += 1
elif a < correct:
print(a,"is lower")
sam += 1
if a == correct:
print("you win")
else:
print("you lose")
app = Tk()
player1 = Entry(app,font=20)
app.minsize(300,300)
player1.pack()
player_2 = Entry(app,font=20)
player_2.pack()
sumbit = Button(app,font=10,text="player 1 sumbit",command=get_1)
sumbit.pack()
guss = Button(app,text="player 2 guess number",font=20,command=Guess)
guss.pack()
app.mainloop()
Writing GUI programs requires a different mindset than writing non-GUI programs.编写 GUI 程序与编写非 GUI 程序需要不同的思维方式。 A loop like the one you created is not appropriate for a GUI.类似于您创建的循环不适合 GUI。 The way GUIs work is that you define functions to be called in response to events, and then the event manager ( mainloop
) is a loop tht waits for events and then dispatches them to the handlers. GUI 的工作方式是定义要调用的函数以响应事件,然后事件管理器 ( mainloop
) 是一个循环,它等待事件,然后将它们分派给处理程序。
So, in your case Guess
should only handle a single guess and not try to loop over a range of guesses.因此,在您的情况下, Guess
应该只处理一次猜测,而不是尝试遍历一系列猜测。 It can keep a global counter for the number of guesses, and update it each time Guess
is called.它可以为猜测次数保留一个全局计数器,并在每次调用Guess
时更新它。
It might look something like this:它可能看起来像这样:
def Guess():
global guesses
global sam
a = int(player_2.get())
player_2.delete(0, "end")
guesses += 1
if a == correct:
print("you win")
elif guesses == 10:
print("you lose")
elif a > correct:
print(a,"is higher")
elif a < correct:
print(a,"is lower")
You need to initialize guesses
to zero when player 1 submits the value, since that designates the start of the game.当玩家 1 提交值时,您需要将guesses
初始化为零,因为这指定了游戏的开始。
def get_1():
global correct
global guesses
correct = int(player1.get())
guesses = 0
player1.pack_forget()
sumbit.pack_forget()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.