tkinter循环问题
我尝试用tkinter做一个手速测试软件,每点击一次按钮就会把一个数字加1,同时还要计时,并且把时间显示在框架上。我觉得这需要用到循环,但我发现一做循环tk就会停止运行,直到循环结束。
有没有大佬帮我改进,这是我的代码
from tkinter import *
import time as t
class App:
def __init__(self, root):
self.frame = Frame(root)
self.frame.pack()
self.time = t.localtime()
self.count = 0
self.var = StringVar()
self.var.set(str(self.count))
self.textlabel = Label(self.frame, textvariable = self.var)
self.click = Button(self.frame, text = 'click me!', command = self.count_click)
self.textlabel.pack()
self.click.pack()
def count_click(self):
self.var.set(str(self.count + 1))
self.count += 1
root = Tk()
root.geometry('150x150')
app = App(root)
root.mainloop()
为什么觉得需要用到循环{:10_293:} kogawananari 发表于 2020-11-3 10:56
为什么觉得需要用到循环
需要查看时间到了没有啊。就算不用循环,用time.sleep也不行啊 需要多线程吧 本帖最后由 kogawananari 于 2020-11-3 15:20 编辑
from tkinter import *
import time as t
class App:
def __init__(self, root):
self.frame = Frame(root)
self.frame.pack()
self.start_time = None
self.secs = 0
self.count = 0
self.var = StringVar()
self.var.set(f'{self.secs}秒{self.count}次')
self.textlabel = Label(self.frame, textvariable = self.var)
self.click = Button(self.frame, text = 'click me!', command = self.count_click)
self.textlabel.pack()
self.click.pack()
def count_click(self):
if self.start_time is None:
self.start_time = t.time()
self.count = self.count + 1
self.var.set(f'{self.secs}秒{self.count}次')
def update_time(self):
if self.start_time is not None:
self.secs = int(t.time() - self.start_time)
self.var.set(f'{self.secs}秒{self.count}次')
self.frame.after(1000,self.update_time)
root = Tk()
root.geometry('150x150')
app = App(root)
app.update_time()
root.mainloop() kogawananari 发表于 2020-11-3 15:19
原来有after方法,学到了,谢谢回答
页:
[1]