首页 > 解决方案 > 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)

标签: pythontkinter

解决方案


我认为这将是一种更好的方法,因为它不需要第二个脚本到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)

推荐阅读