我目前对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()
有什么建议吗?
答案 0 :(得分:0)
运行子进程,并将回调链接到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'
您可以根据需要添加更多具有更多操作的按钮。