python - 将脚本连接/处理到 PySimpleGUI 按钮
问题描述
你们能帮我知道如何在我的 PySimpleGui 脚本中连接一个按钮,当按下/单击运行按钮时,它将执行另一个 python 脚本。
现在,我一直在阅读关于 GUI 脚本中的 Subprocess 和 command = os.popen 的内容。
layout = [[ sg.Text('Click the button to launch Program')],
[sg.Button('Launch')]]
win1 = sg.Window('My new window').Layout(layout)
win2_activate = False
while True:
ev1, vals1 = win1.Read()
if ev1 is None or ev1 == 'Cancel':
break
if not win2_activate and ev1 == 'Launch':
win1.Hide()
win2_activate = True
layout2 = [[sg.Text('Report Auto')],
[sg.Input(do_not_clear=True)],
[sg.Text('', key='_OUTPUT_')],
[sg.Button('Run'), sg.Button('Cancel')]]
win2 = sg.Window('Window2').Layout(layout2)
while True:
ev2, vals2 = win2.Read()
if ev2 is None or ev2 =='Cancel':
win2_activate = False
win2.Close()
win1.UnHide()
break
在我的 pysimplegui 脚本中,我还没有包含子进程或任何库,因为我只是不知道在哪里做。任何帮助将是最受欢迎的!
解决方案
这是您问题的完整答案,一个 PySimpleGUI 程序。该程序允许您输入命令。然后按一个按钮。按下按钮时,命令为“运行”,输出显示在窗口中。
import subprocess
import sys
import PySimpleGUI as sg
def main():
layout = [ [sg.Text('Enter a command to execute (e.g. dir or ls)')],
[sg.Input(key='_IN_')], # input field where you'll type command
[sg.Output(size=(60,15))], # an output area where all print output will go
[sg.Button('Run'), sg.Button('Exit')] ] # a couple of buttons
window = sg.Window('Realtime Shell Command Output', layout)
while True: # Event Loop
event, values = window.Read()
if event in (None, 'Exit'): # checks if user wants to exit
break
if event == 'Run': # the two lines of code needed to get button and run command
runCommand(cmd=values['_IN_'], window=window)
window.Close()
# This function does the actual "running" of the command. Also watches for any output. If found output is printed
def runCommand(cmd, timeout=None, window=None):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in p.stdout:
line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
output += line
print(line)
window.Refresh() if window else None # yes, a 1-line if, so shoot me
retval = p.wait(timeout)
return (retval, output) # also return the output just for fun
if __name__ == '__main__':
main()
推荐阅读
- python - 函数参数上的 PyCharm 代码完成
- python - 如何从较大的 pytorch 张量中提取张量到 numpy 数组或列表
- python-requests - 如何在 Python 请求中使用 3DS 信用卡确认?
- python - SQLAlchemy:SQLite 中的回滚事务
- function - Glob 作为 shell 函数的参数
- visual-studio-code - 为什么 VSCode 乳胶片段不起作用(// 字符)?
- spring - Spring Boot 是否支持基于 URL 模式的多种内容协商策略
- c# - 使用按钮重新排序 GridView
- matlab - MATLAB App Designer 代码错误(针对 MCC DAQ)
- cordova - Capacitor Motion 插件未显示为已安装