2016-11-24 90 views
0

我有2个python文件。一个是helloworld.py,第二个是main.py.在main.py中有按钮。当我点击那个按钮时,我想把helloworld.py的结果打印到文本框中。Python tkinter在GUI上显示CLI结果

helloworld.py

打印( “世界你好”)

所以我想打印招呼到main.py文本字符串世界

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() 

回答

1

使用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() 
+0

谢谢你的工作。但是,现在我正在获得整个输出。我想要的是,GUI应该反复打印输出,就像它在终端上打印一样。 –

+0

我不明白你的意思,我想你会考虑一些比打印'hello world'更复杂的东西。你能举个例子吗? –

+0

我有flash.py python文件,通过我从Flashair获取图像。对于想要迭代循环 –