2016-11-24 214 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獲取圖像。對於想要迭代循環 –