在python可视化界面Tkinter中,用文本框输出日志信息。
大致思路,不断将日志信息输入到文本框最前面,这样最前面就是最新的信息
关键代码,在Text组件中有insert()这个方法,第一个参数索引,我们需要插入到文本最顶部,传入1.0即可,这里的1.0代表第1行,第0个字符。
self.tk_text_lb4no8xs.insert(0.0, info + "\r\n")
演示
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
import datetime
import threading
from time import sleep
from tkinter import *
from tkinter.ttk import *
class WinGUI(Tk):
def __init__(self):
super().__init__()
self.__win()
self.tk_text_lb4no8xs = self.__tk_text_lb4no8xs()
self.tk_button_start = self.__tk_button_start()
self.tk_button_stop = self.__tk_button_stop()
def __win(self):
self.title("文本框信息输出")
# 设置窗口大小、居中
width = 621
height = 271
screenwidth = self.winfo_screenwidth()
screenheight = self.winfo_screenheight()
geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
self.geometry(geometry)
self.resizable(width=False, height=False)
def __tk_text_lb4no8xs(self):
text = Text(self)
text.place(x=10, y=120, width=601, height=143)
return text
def __tk_button_start(self):
btn = Button(self, text="开始")
btn.place(x=20, y=30, width=90, height=40)
return btn
def __tk_button_stop(self):
btn = Button(self, text="停止")
btn.place(x=440, y=30, width=90, height=40)
return btn
class Win(WinGUI):
flag = False
def __init__(self):
super().__init__()
self.__event_bind()
def __event_bind(self):
self.tk_button_start.config(command=self.start)
self.tk_button_stop.config(command=self.stop)
def start(self):
self.flag = True
threading.Thread(target=self.print_info).start()
def stop(self):
self.flag = False
def print_info(self):
while self.flag:
info = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.tk_text_lb4no8xs.insert(1.0, info + "\r\n")
sleep(1)
if __name__ == "__main__":
win = Win()
win.mainloop()
|