PyQt5 打开新窗口并执行命令示例代码
以下是一个示例代码,其中包含一个主窗口和一个在点击按钮时打开的新窗口。新窗口包含一个文本框和一个按钮,按下按钮后会执行一个命令并将输出显示在文本框中。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, QPushButton
import subprocess
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Main Window')
self.setGeometry(100, 100, 500, 500)
# Create a button to open the new window
btn = QPushButton('Open New Window', self)
btn.clicked.connect(self.open_new_window)
def open_new_window(self):
# Create a new window
new_window = QWidget()
new_window.setWindowTitle('New Window')
new_window.setGeometry(200, 200, 300, 300)
# Create a layout for the new window
layout = QVBoxLayout()
# Create a text edit widget
text_edit = QTextEdit()
layout.addWidget(text_edit)
# Create a button to execute a command
btn = QPushButton('Execute Command', new_window)
btn.clicked.connect(lambda: self.execute_command(text_edit))
layout.addWidget(btn)
new_window.setLayout(layout)
# Show the new window
new_window.show()
def execute_command(self, text_edit):
# Example command to execute
command = 'ls -l'
# Execute the command and capture the output
output = ''
try:
output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as e:
output = str(e.output)
# Display the output in the text edit widget
text_edit.setText(output.decode('utf-8'))
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
请注意,此示例代码仅用于演示目的。在实际使用中,您需要仔细考虑安全性和异常处理,并仅执行您信任的命令。
原文地址: https://www.cveoy.top/t/topic/oJOc 著作权归作者所有。请勿转载和采集!