python - 通过按下 tkinter 按钮启动子进程
问题描述
我目前对 Python 和一般编码是全新的,只是想尝试制作 4 个按钮的布局,单击时打开不同的程序。截至目前,我的代码如下所示。
from tkinter import *
import os
import subprocess
root=Tk()
root.geometry('750x650')
root.title('Test')
topFrame = Frame(root)
topFrame.pack(side=TOP, fill='both')
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM, fill='both')
button1 = Button(topFrame, text="Button1", fg="black")
button2 = Button(topFrame, text="Button2", fg="black")
button3 = Button(bottomFrame, text="Button3", fg="black")
button4 = Button(bottomFrame, text="Button4", fg="black")
button1.config(height=21, width=52)
button2.config(height=21, width=52)
button3.config(height=21, width=52)
button4.config(height=21, width=52)
button1.pack(side='left', fill='both')
button2.pack(side='right', fill='both')
button3.pack(side='left', fill='both')
button4.pack(side='right', fill='both')
app = Application(root)
root.mainloop()
有什么建议么?
解决方案
运行子进程和将回调链接到 tkinter 按钮是两件不同的事情;
launching 1
首先,我将解决链接回调:在这里,当您按下按钮时,我们将在控制台中打印。
import os
import subprocess
import tkinter as tk
def launch_1(): # function to be called
print('launching 1')
root = tk.Tk()
root.geometry('750x650')
root.title('Launch Test')
button1 = tk.Button(root, text="Button1", command=launch_1) # calling from here when button is pressed
button1.pack(side='left', fill='both')
root.mainloop()
输出是:
launching 1
现在让我们启动一个子进程;例如 ping 堆栈溢出。
示例取自这里。
import os
import subprocess
import tkinter as tk
def launch_1():
print('launching 1') # subprocess to ping host launched here after
p1 = subprocess.Popen(['ping', '-c 2', host], stdout=subprocess.PIPE)
output = p1.communicate()[0]
print(output)
root = tk.Tk()
root.geometry('750x650')
root.title('Launch Test')
button1 = tk.Button(root, text="Button1", command=launch_1)
button1.pack(side='left', fill='both')
host = "www.stackoverflow.com" # host to be pinged
root.mainloop()
现在的输出是:
launching 1
b'PING stackoverflow.com (151.101.65.69): 56 data bytes\n64 bytes from 151.101.65.69: icmp_seq=0 ttl=59 time=166.105 ms\n64 bytes from 151.101.65.69: icmp_seq=1 ttl=59 time=168.452 ms\n\n--- stackoverflow.com ping statistics ---\n2 packets transmitted, 2 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 166.105/167.279/168.452/1.173 ms\n'
您可以根据需要添加更多具有更多操作的按钮。
推荐阅读
- php - 嵌入式表单 - Symfony 4
- hive - 如何在 collect_list、collect_set 或 group_concat 之后修复 Hive 错误?
- node.js - 使用角度服务将基本身份验证传递给rest api
- parsing - Pandoc Markdown to Markdown - 防止添加反斜杠字符
- javascript - laravel 包含基于语言的js脚本
- javascript - 我如何编写一个将数据加载到谷歌地图中的函数,并通过单击地图图标来执行另一项任务?
- python - 为什么我在while循环中将变量设置为false会给我错误而不是停止循环
- mysql - 如何在mysql上选择每辆出租车的最新位置
- php - 如何使用php禁用post unicode字符
- ios - iOS 圆形渐变