gpt4 book ai didi

python - Tkinter 机智 while 循环 (python 3)

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:18 26 4
gpt4 key购买 nike

首先,我创建了一个带有一些按钮的窗口,并定义了它们的命令。一切正常,直到我添加 while 循环来检查是否按下了任何按钮,然后转到下一步。但随后窗口不会显示,并且循环将永远运行。我还想知道是否有更好的替代我的代码。

from tkinter import *

Round = 0

def blackC():
global Round
print ('0')
x = 0
Round += 1

def brownC():
global Round
print ('1')
x = 1
Round +=1

def redC():
global Round
print ('2')
x = 2
Round += 2

def win():
window = Tk()
window.geometry ('500x500')
window.title('HELLO')
blackB = Button(text = 'BLACK', command=blackC, width=7, height=3, bd=5)
blackB.place(x=1, y=1)
brownB = Button(text = 'BROWN', command=brownC, width=7, height=3, bd=5)
brownB.place(x=86, y=1)
redB = Button(text = 'RED', command=redC, width=7, height=3, bd=5)
redB.place(x=172, y=1)
window.mainloop()

while (Round == 0):
win()
while (Round < 3):
if (Round == 1):
y = x * 10
print ('y')
elif (Round == 2):
y += x
print ('y')

最佳答案

我不知道你所说的进入下一步到底是什么意思,但你肯定误解了 tkninter 的工作原理。您在主循环 window.mainloop() 中缺少括号。而且你不想在循环中调用它,因为mainloop是一个循环函数。所以你只需每次运行一次,然后它就会无限运行。因此,您的代码必须每次只运行一次函数 win()。

from tkinter import *

Round=0

def button(type):
global Round
print (str(type))
x = type
Round += type

def win():
window = Tk()
window.geometry ('500x500')
window.title('HELLO')
blackB = Button(text = 'BLACK', command=lambda: button(0), width=7, height=3, bd=5)
blackB.place(x=1, y=1)
brownB = Button(text = 'BROWN', command=lambda: button(1), width=7, height=3, bd=5)
brownB.place(x=86, y=1)
redB = Button(text = 'RED', command=lambda: button(2), width=7, height=3, bd=5)
redB.place(x=172, y=1)
window.mainloop

win()

您要求更好的代码,因此我将您的按钮函数重写为一个,它只接受类型参数并将其称为 lambda 函数(看一下: http://www.diveintopython.net/power_of_introspection/lambda_functions.html 。对于较大的项目,最好将 tkinter 窗口作为一个类,但这就足够了。

关于python - Tkinter 机智 while 循环 (python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com