使用繁體中文,"import subprocess process = subprocess.Popen( ['udp-sender.exe', '--file', save_path, '--port', '8500'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, creationflags=subprocess.CREATE_NO_WINDOW ) # 讀取輸出 output, _ = process.communicate() print(output)",# 讀取輸出後的資料,要如何呈現在UI界面上?
要在 UI 界面上呈現 subprocess 執行的輸出,你可以根據所使用的 GUI 框架選擇不同的方式。這裡是幾個常見的 GUI 框架及其實現方法:
如果你使用 Tkinter,可以在一個文本框中顯示輸出:
import subprocess
import tkinter as tk
from tkinter import scrolledtext
def run_command():
process = subprocess.Popen(
['udp-sender.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
output, _ = process.communicate()
output_text.delete(1.0, tk.END) # 清空文本框
output_text.insert(tk.END, output) # 插入新輸出
# 建立主窗口
root = tk.Tk()
root.title("命令執行結果")
# 創建一個可滾動的文本框
output_text = scrolledtext.ScrolledText(root, width=50, height=20)
output_text.pack()
# 按鈕觸發命令執行
run_button = tk.Button(root, text="執行命令", command=run_command)
run_button.pack()
root.mainloop()
如果你使用 PyQt,則可以使用 QTextEdit 來顯示輸出:
import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QTextEdit, QPushButton, QVBoxLayout, QWidget
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.layout = QVBoxLayout()
self.output_text = QTextEdit(self)
self.layout.addWidget(self.output_text)
self.run_button = QPushButton('執行命令', self)
self.run_button.clicked.connect(self.run_command)
self.layout.addWidget(self.run_button)
self.setLayout(self.layout)
self.setWindowTitle('命令執行結果')
self.show()
def run_command(self):
process = subprocess.Popen(
['udp-sender.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
output, _ = process.communicate()
self.output_text.setPlainText(output) # 更新文本框內容
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
如果你使用 Kivy,則可以在 Label 中顯示輸出:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
import subprocess
class MyLayout(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.output_label = Label(text='命令輸出會顯示在這裡')
self.add_widget(self.output_label)
self.run_button = Button(text='執行命令')
self.run_button.bind(on_press=self.run_command)
self.add_widget(self.run_button)
def run_command(self, instance):
process = subprocess.Popen(
['udp-sender.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
output, _ = process.communicate()
self.output_label.text = output # 更新標籤內容
class MyApp(App):
def build(self):
return MyLayout()
if __name__ == '__main__':
MyApp().run()
根據你使用的 GUI 框架,選擇相應的代碼片段,並確保有合適的 save_path 變數來指定要傳送的文件路徑。