Skip to main content
 首页 » 编程设计

python之打印到 Tkinter GUI 而不是 Eclipse 控制台的脚本

2024年08月28日28del

我是一个非常的新手程序员,对 python 和 tkinter 很感兴趣。

我已经阅读了一些关于制作基于 Tk GUI 的基本程序的教程。 我正在尝试将“tk 模板”程序改编成基本的 ping 实用程序,以供娱乐/学习。我的 IDE 是 eclipse with PyDev,我的环境是 gnome3/ubuntu13.10

这是我的脚本:

#! /usr/bin/python 
 
#import Tkinter as tk 
from Tkinter import * 
import pyping 
#import multiprocessing 
 
class App: 
    def __init__(self,master): 
        frame = Frame(master) 
        frame.pack() 
        self.lbl = Label(frame, text="Hello World!\n") 
        self.lbl.pack() 
        self.button = Button(frame, text="Quit",bg="red", fg="white", command=frame.quit) 
        self.button.pack(side=LEFT) 
        self.hi_there = Button(frame, text="Issue PING", command=self.do_ping) 
        self.hi_there.pack(side=LEFT) 
 
    def do_ping(self): 
        pyping.ping.func_defaults = (1000, 10, 55) 
        h = pyping.ping('g.co') 
        for i in h.output: 
            print i 
 
#    def draw_console(self): 
 
root = Tk() 
 
root.title("title bar text") 
root.geometry("200x100") 
app = App(root) 
root.mainloop() 

当我点击“Issue Ping”按钮时

.

它将此打印到 eclipse 调试控制台(如预期的那样):

pydev debugger: starting 
 
PYTHON-PING g.co (74.125.229.168): 55 data bytes 
241 bytes from g.co (74.125.229.163): icmp_seq=0 ttl=52 time=94.4 ms 
241 bytes from g.co (74.125.229.165): icmp_seq=1 ttl=52 time=88.7 ms 
241 bytes from g.co (74.125.229.162): icmp_seq=2 ttl=52 time=89.9 ms 
241 bytes from g.co (74.125.229.161): icmp_seq=3 ttl=52 time=87.9 ms 
241 bytes from g.co (74.125.229.160): icmp_seq=4 ttl=52 time=89.0 ms 
241 bytes from g.co (74.125.229.169): icmp_seq=5 ttl=52 time=89.8 ms 
241 bytes from g.co (74.125.229.167): icmp_seq=6 ttl=52 time=87.9 ms 
241 bytes from g.co (74.125.229.166): icmp_seq=7 ttl=52 time=88.6 ms 
241 bytes from g.co (74.125.229.164): icmp_seq=8 ttl=52 time=87.2 ms 
241 bytes from g.co (74.125.229.174): icmp_seq=9 ttl=52 time=88.9 ms 
 
----g.co PYTHON PING Statistics---- 
10 packets transmitted, 10 packets received, 0.0% packet loss 
round-trip (ms)  min/avg/max = 87.188/89.226/94.367 

.

我的目标是能够在 tk gui 内的“文本字段”中看到控制台输出。

该怎么做?

请您参考如下方法:

最简单的解决方案是添加文本小部件,但这不是唯一的解决方案。

添加文本小部件后,将打印语句替换为:

self.text_widget.insert("end", i + "\n") 

请注意,在以下两种情况之一发生之前​​,输出不会出现:

  1. 循环结束,将控制权交还给事件循环
  2. 您在循环的每次迭代期间调用self.update_idletasks,这使事件循环有机会处理重绘事件。