python - tkinter incrementally display infos in scrolledtext from another file
问题描述
Is it possible to display the result of any variable in another file to the scrolltext. My question is: Image I have two python files. py1.py is the main file which contains only scrolledtext widget. And what I need to realize is that I want the result of any variable in py2.py to be consciously (incrementally) displayed in the scrolledtext widget (which is embedded in py1.py).
# -*- coding: utf-8 -*-
"""
py1.py
"""
import tkinter as tk
from tkinter import scrolledtext
win = tk.Tk()
text_area = scrolledtext.ScrolledText(win)
# for ii in range(100000):
# mystr = "Step " + str(ii) + "\n"
# text_area.insert(tk.END, mystr)
exec(open("py2.py").read())
text_area.see(tk.END)
text_area.pack()
win.mainloop()
"""
py2.py
"""
import tkinter as tk
from py1 import text_area
for ii in range(100000):
mystr = "Step " + str(ii) + "\n"
text_area.insert(tk.END, mystr)
解决方案
我认为这将是一种更好的方法,因为它不需要第二个脚本到import
第一个脚本来访问其变量(无论如何这都行不通)。而是py1.py
导入第二个脚本并在其中调用一个函数并将变量作为参数传递。这就是我的意思:
"""
py1.py
"""
import py2
import tkinter as tk
from tkinter import scrolledtext
win = tk.Tk()
text_area = scrolledtext.ScrolledText(win)
text_area.pack()
btn = tk.Button(text='Display Results', command=lambda: py2.add_results(text_area))
btn.pack()
win.mainloop()
第二个脚本:
"""
py2.py
"""
import tkinter as tk
def add_results(text_area):
for ii in range(100000):
mystr = "Step " + str(ii) + "\n"
text_area.insert(tk.END, mystr)
text_area.see(tk.END)
text_area.update_idletasks() # Update display.
更新
为了防止add_results()
函数中的紧密循环使您的应用程序在循环完成之前冻结,您需要使用通用after()
小部件方法来安排对函数的重复调用,直到完成。
所以这是第二个脚本中函数的一个版本,展示了如何做到这一点:
"""
py2.py - version 2.0
"""
import tkinter as tk
def add_results(text_area, ii=0):
if ii < 100000: # Not Done?
mystr = f"Step {ii}\n"
text_area.insert(tk.END, mystr)
text_area.see(tk.END)
text_area.update_idletasks() # Update display.
ii += 1
# Call this func again in 100 ms (0.1 sec).
text_area.after(100, add_results, text_area, ii)
推荐阅读
- python - 合并同一行的数据框
- javascript - Div 跟随带死区的光标
- azure-devops - 如何获得有关 Azure DevOps PR 问题状态更改的通知
- docker - Docker - FROM 需要一个或三个参数
- vb.net - 如何更改 MsgBox 按钮语言
- python - 使用带有 Python Flask 的 HTML 表单搜索 MongoDB 集合
- haskell - Void 是初始元素还是零元素?
- database - phpunit 测试中的 Laravel assertDatabaseHas 不起作用
- python-3.x - 当我想限制它只使用一个 CPU 线程时,为什么 pytorch .backward() 方法会多占用两个 CPU 线程?
- parquet - Parquet 原始文件内容与数据块中显示的内容相比似乎不完整