Python Tkinter显示CLI在GUI上结果



我有2个python文件。一个是helloworld.py,第二个是main.py。在main.py中有按钮。当我单击该按钮时,我想打印helloworld.py的结果。

helloworld.py

print(" Hello World")

所以我想将Hello World String打印到Main.py Textbox

from tkinter import *
import os
root= Tk()
root.title("My First GUI")
root.geometry("800x200")
frame1=Frame(root)
frame1.grid()
def helloCallBack():
     result = os.system('python helloworld.py')
     if result==0:
         print("OK")
         text1.insert(END,result)        
     else:
         print("File Not Found")
label1 = Label(frame1, text = "Here is a label!")
label1.grid()
button1 = Button(frame1,text="Click Here" , foreground="blue",command= helloCallBack)
button1.grid()
text1 = Text(frame1, width = 35, height = 5,borderwidth=2)
text1.grid()
radiobutton1 = Radiobutton(frame1, text= "C Programming", value=0)
radiobutton1.grid()
radiobutton2 =Radiobutton(frame1, text= "Python Programming")
radiobutton2.grid()
root.mainloop()

使用subprocess.check_output代替os.system

from tkinter import *
from subprocess import check_output, CalledProcessError
root = Tk()
text1 = Text(root)
text1.pack()
def command():
    try:
        res = check_output(['python', 'helloworld.py'])
        text1.insert(END, res.decode())
    except CalledProcessError:
        print("File not found")
Button(root, text="Hello", command=command).pack()
root.mainloop()

最新更新