gpt4 book ai didi

Python 记录到 Tkinter 文本小部件

转载 作者:IT老高 更新时间:2023-10-28 20:33:42 27 4
gpt4 key购买 nike

有没有人有一个例子来说明如何在 Python 中设置日志到 Tkinter 文本小部件?我已经在几个应用程序中看到了它,但无法弄清楚如何将日志记录定向到日志文件以外的任何内容。

最佳答案

除了上述答案之外:尽管有很多建议的解决方案(此处和 this other thread 中),但我自己努力完成这项工作。最终我遇到了this text handler class by Moshe Kaplan ,它使用 ScrolledText小部件(这可能比 ScrollBar 方法更容易)。

我花了一些时间才弄清楚如何在线程应用程序中实际使用 Moshe 的类。最后,我创建了一个最小的演示脚本,展示了如何使它全部工作。因为它可能对其他人有帮助,所以我在下面分享它。在我的特殊情况下,我想登录 both GUI 和文本文件;如果您不需要,只需删除 logging.basicConfig 中的 filename 属性。

import time
import threading
import logging
try:
import tkinter as tk # Python 3.x
import tkinter.scrolledtext as ScrolledText
except ImportError:
import Tkinter as tk # Python 2.x
import ScrolledText

class TextHandler(logging.Handler):
# This class allows you to log to a Tkinter Text or ScrolledText widget
# Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06

def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
# Store a reference to the Text it will log to
self.text = text

def emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(tk.END, msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)

class myGUI(tk.Frame):

# This class defines the graphical user interface

def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.build_gui()

def build_gui(self):
# Build GUI
self.root.title('TEST')
self.root.option_add('*tearOff', 'FALSE')
self.grid(column=0, row=0, sticky='ew')
self.grid_columnconfigure(0, weight=1, uniform='a')
self.grid_columnconfigure(1, weight=1, uniform='a')
self.grid_columnconfigure(2, weight=1, uniform='a')
self.grid_columnconfigure(3, weight=1, uniform='a')

# Add text widget to display logging info
st = ScrolledText.ScrolledText(self, state='disabled')
st.configure(font='TkFixedFont')
st.grid(column=0, row=1, sticky='w', columnspan=4)

# Create textLogger
text_handler = TextHandler(st)

# Logging configuration
logging.basicConfig(filename='test.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')

# Add the handler to logger
logger = logging.getLogger()
logger.addHandler(text_handler)

def worker():
# Skeleton worker function, runs in separate thread (see below)
while True:
# Report time / date at 2-second intervals
time.sleep(2)
timeStr = time.asctime()
msg = 'Current time: ' + timeStr
logging.info(msg)

def main():

root = tk.Tk()
myGUI(root)

t1 = threading.Thread(target=worker, args=[])
t1.start()

root.mainloop()
t1.join()

main()

Github Gist 链接到上述代码:

https://gist.github.com/bitsgalore/901d0abe4b874b483df3ddc4168754aa

关于Python 记录到 Tkinter 文本小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318742/

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