制作一个盒子并将输入存储在变量 tkinter 中

Make a box and store the input in a variable tkinter

我正在尝试在 tkinter 上制作一个带有 GUI 的 ping 工具。问题是我想创建一个框,您可以在其中输入一个 Web 域,然后单击 ping 并 ping 到该 Web。现在我必须更改网络以在代码 (V1.0) 上执行 ping 操作,但我真的尝试进行上述更改,但它们似乎不起作用。

这是原代码:

#Imports
from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread


def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

#Ping printed on tkinter window root
def commande():
    cmd = 'ping -c 10 google.com'
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)
    for line in iter(p.stdout.readline, ''):
    result.configure(text=line)

#tkinter code
root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda:start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()

一个不工作的版本:

from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

#intput on the console
u = input('Website to ping: ')

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()


def commande():
    cmd = 'ping -c 10 ' + u
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)#
    for line in iter(p.stdout.readline, ''): #changes the text printed instead of printing multiple times
        result.configure(text=line)#

root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda: start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()

'not working version' 有 'problem' 输入是写在控制台上的。这个想法是创建一个标签并在那里输入文本。 我知道这可能不是提出此类问题的最佳场所,因为我似乎只想完成工作,但请相信我,我真的已经尝试过了。 谢谢

PD:我从 tkinter 开始。

subprocess.check_output 应该足以满足您的需求 https://pymotw.com/2/subprocess/index.html#module-subprocess A simple program follows that runs the command when the button is pressed, and prints the output. I'll leave something for you to do, i.e. configure the text on a Label http://effbot.org/tkinterbook/label.htm 并且您还应该为不是有效网站的条目添加一些代码。

import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

import subprocess

def button_callback():
    ent_contents=ent.get()
    output=subprocess.check_output("ping -c 10 "+ent_contents,
                                    shell=True)
    print "*****after", output, "\n"

root=tk.Tk()
ent=tk.Entry(root)
ent.grid(row=0, column=0)
ent.focus_set()

tk.Button(root, text="ping website", bg="lightblue",
          command=button_callback).grid(row=1, column=0)
tk.Button(root, text="Exit Program", bg="orange",
          command=root.quit).grid(row=2, column=0)

root.mainloop()