python-3.x 为什么Tkinter窗口不显示?

0aydgbwb  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(213)

我有一个tkinter窗口,在一个文本框和一个可点击的按钮上显示你的cps。cps是用'while True:'循环计算的,但不知何故阻止了tkinter窗口的出现。当程序运行时,不会出现错误。下面是我的代码:

from tkinter import *
from time import sleep
c=0
cps1=0
cps2=0
cps=0
def click():
    global c
    c +=1
    text.delete(0.0, END)
    text.insert(END, str(cps))
window = Tk()
text = Text(window, width=10, height=10)
buttonA = Button(window, text='Click Here!', command=click)
text.pack()
buttonA.pack()
while True:
    cps1 = c
    sleep(1)
    cps2 = c
    cps = (cps2-cps1)
qpgpyjmq

qpgpyjmq1#

您没有看到窗口,因为您忘记添加window.mainloop()
此外,你应该使用.after而不是无限循环,因为没有其他东西会被执行。你可以这样做:

from tkinter import *
c=0
cps1=0
cps2=0
cps=0
def click():
    global c
    c +=1
    text.delete("1.0", END)
    text.insert(END, str(cps))
    
def update():
    global c, cps1, cps2, cps
    window.after(1000, update)
    cps2 = c
    cps = (cps2-cps1)
    cps1 = c

window = Tk()
text = Text(window, width=10, height=10)
buttonA = Button(window, text='Click Here!', command=click)
text.pack()
buttonA.pack()
update()
window.mainloop()

understanding mainloop

相关问题