我想在Python中尝试一些图形用户界面的东西。我是Python和PySimpleGUI的新手。我决定做一个程序,当给定一个IP地址时,它会ping它,并在弹出窗口中显示回复。(我知道非常简单。)
然而,它工作得很好:它在控制台中显示响应,但我想在GUI中显示它。
是否可以将控制台输出保存在一个变量中,并以这种方式在GUI中显示它?
我希望这个问题是有意义的:)
这是我的代码:
#1 Import:
import PySimpleGUI as sg
import os
#2 Layout:
layout = [[sg.Text('Write the IP-address you want to ping:')],
[sg.Input(key='-INPUT-')],
[sg.Button('OK', bind_return_key=True), sg.Button('Cancel')]]
#3 Window:
window = sg.Window('Windows title', layout)
#4 Event loop:
while True:
event, values = window.read()
os.system('ping -n 1 {}'.format(values['-INPUT-']))
if event in (None, 'Cancel'):
break
#5 Close the window:
window.close()发布于 2021-09-05 15:45:40
我在这里找到了答案:https://stackoverflow.com/a/57228060/4954813
我已经用python 3.9测试过了,它的效果很棒;-)
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()https://stackoverflow.com/questions/64680384
复制相似问题