首页 > 解决方案 > 通过按下 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()

有什么建议么?

标签: pythontkintercallbacksubprocess

解决方案


运行子进程和将回调链接到 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'

您可以根据需要添加更多具有更多操作的按钮。


推荐阅读