2011-01-30 63 views
1

我有一个列表,如:打印在python字符串从列表到GUI

list = ['one', 'two', 'three', 'four'] 

和列表项,每10分钟(记住这一点)改变。

我需要一个背景图片,我可以从列表打印每个项目的GUI。我可以这样做

for item in list: 
    print item 

我试着用tkinter,但我有一些问题与主循环()。当我做

for item in list: 

    root = Tk() 
    canvas = Canvas(width = 300, height = 200, bg = 'yellow') 
    canvas.pack(expand = YES, fill = BOTH) 
    gif1 = PhotoImage(file = 'myImage.gif') 
    canvas.create_image(0, 0, image = gif1, anchor = NW) 

    # print item from my list 
    w = Label(root, text=item) 
    w.pack() 

    root.mainloop() 

与图像的Tkinter的GUI显示而只用文字“一”(从我的列表中的第一项)。当我关闭gui时,另一个窗口会弹出“two”,当我关闭那个窗口时,会出现“three”......并且至少是“four”。 这是合乎逻辑的,因为我是for循环中的全部时间,并且我的列表中的每个项目都会生成gui。

我的问题:我如何更新GUI?我的清单中的项目每10分钟更换一次。我需要遍历我的列表并在一个GUI窗口中打印所有项目。 10分钟后,我想再次遍历我的列表并重新更新gui。

我该怎么做?

+0

您必须了解GUI如何工作。阅读一些介绍。 – 2011-01-30 17:25:48

+0

在“打印每件物品”的情况下,“打印”是什么意思?你想让它们在GUI中一次显示一个,还是你真的想把它们打印到stdout? – 2011-01-30 20:29:21

回答

1

你是因为你的循环定义在主循环和所有其余4个获得窗户。作为一种替代的尝试:

root = Tk() 
canvas = Canvas(width = 300, height = 200, bg = 'yellow') 
canvas.pack(expand = YES, fill = BOTH) 
gif1 = PhotoImage(file = 'myImage.gif') 
canvas.create_image(0, 0, image=gif1, anchor = NW) 

item=" ".join(list) 
w = Label(root, text=item) 
w.pack() 

root.mainloop() 

,打印列表作为行的所有项目。下一步是在列表更改时重新绘制主窗口。我不是Tk专家,所以我无法帮助。

尝试this stuff学习如何Tk的正确使用。

0

这里有两个线程,如果你需要执行长计算或阻塞的IO,这是有用做到这一点的方法之一。设置一个队列以在主GUI线程和“馈线”线程之间进行通信。您可以使用root.after()函数从队列中读取主循环将定期调用的函数。所有TK方法都必须在调用root.mainloop()的线程中调用(否则程序可能会崩溃)。

import threading 
from Tkinter import Tk, Canvas, Label 
import Queue 
import time 
from itertools import cycle 

# Feeder thread puts one word in the queue every second 
source_iter = cycle(['one', 'two', 'three', 'four', 'five', 'six']) 
queue = Queue.Queue() 

def source(): 
    for item in source_iter: 
     queue.put(item) 
     time.sleep(1.) 

source_thread = threading.Thread(target=source) 
source_thread.setDaemon(True) 
source_thread.start() 

# Main thread reads the queue every 250ms 
root = Tk() 
w = Label(root, text='') 
w.pack() 
def update_gui(): 
    try: 
     text = queue.get_nowait() 
     w.config(text=text) 
    except Queue.Empty: 
     pass 
    root.after(250, update_gui) 
update_gui() 
root.mainloop()