【问题标题】:Launching a subprocess by pressing a tkinter button通过按下 tkinter 按钮启动子进程
【发布时间】:2018-09-11 04:16:37
【问题描述】:

我目前对 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()

有什么建议吗?

【问题讨论】:

  • 您到底在寻找什么?您还没有添加按钮按下的回调函数,您希望触发哪些程序?
  • 我尝试使用 App 类:但我得到的只是错误
  • 我只是试图让按钮触发 CCleaner 和 Adwcleaner 等程序的启动。我添加了一个 command=self.openfile 并无法让它工作
  • 我没有看到您的代码中定义了任何名为 Application 的类,如果您还没有定义任何类,请删除行 app = Application(root)
  • 是的,我在发布后删除了它。因为我看到它不应该在那里,因为它没有被定义。

标签: python tkinter callback subprocess


【解决方案1】:

运行子进程和将回调链接到 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 堆栈溢出。
example taken from here.

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'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多