Skip to main content
 首页 » 编程设计

python之我有两个 .py 文件。如何将一个程序的多行输出转换为另一个程序 GUI 的 tkinter 文本

2025年04月02日34exmyth

GUI 包含一个运行按钮,该按钮应根据用户需要多次运行第一个程序并以 tkinter 文本显示输出。

我的代码(第二个 .py 文件):

from tkinter import* 
from tkinter import ttk 
import Random Game 
 
root = Tk() 
root.title("Random Game 1.0") 
 
quote = "Long \nRandom \nText \nGenerated \nBy \nRandom Function \nAnd \nControl Structures" 
 
frame = Frame(root) 
 
labelText = StringVar() 
 
label = Label(frame, textvariable=labelText).pack() 
button = Button(frame, text="Click to Run").pack() 
 
labelText.set("Random Game 1.0") 
Label(root, text ="") 
 
T = Text(root) 
 
frame.pack() 
 
T.pack() 
T.insert(END, quote) 
 
root.mainloop() 

我想要第一个程序的输出,它在“另一个(第二个程序)的 tkinter 文本中每次都是随机的,而不是上面代码中提到的引号行。

请您参考如下方法:

输出第一个程序到txt文件。

通过检查上次修改时间从该 txt 文件读入 tkinter GUI,以避免互斥问题。

因此:

# Prog 1: 
 
file = open("log.txt", "w") 
# code that writes there 
 
# Prog 2: 
 
file = open("log.txt", "r") 
# use data to show in the tkinter with its mainloop for example 
# in mainloop()... 
#    ..... 
     if other_prog_has_written_something_new  : 
         data = file.readlines() 
         useDataInGUI(data)