2015-04-16 79 views
0

我有一個問題在tkinter環境(樹莓上的蟒蛇3.2)設置文件名。要指定我的意思,我會用我的代碼:Tkinter文件名與StringVar

from tkinter import Tk, Canvas, StringVar 
from PIL import ImageTk, Image 
from threading import Thread 

class proc(Thread): 
    def __init__(self): 
     Thread.__init__(self) 

    def run(self): 
     self.root=tkinter.Tk() 
     self.labelstring = StringVar() 
     self.labelstring.set('Foo') 

     self.path = StringVar() 
     self.path.set('cold.jpg') 

     canvas = Canvas(self.root, width=888, height=600) 
     canvas.pack() 

     im = Image.open(self.path) #<-- does not work 
     canvas.image = ImageTk.PhotoImage(im) 
     canvas.create_image(0, 0, image=canvas.image, anchor='nw') 

     label = tkinter.Label(self.root,textvariable=self.labelstring) 
     label.pack() 
     self.root.mainloop() 


app = proc() 
app.start() 


for i in range(0, 10): 
    time.sleep(5) 
    proc.labelstring.set(i) 

,我改變labelstring.set(i)工作正常,但什麼行不通通過path.set('image.jpg')發送文件名標籤的一部分。我知道,文件類型不是這樣的路徑,它是一個tkinter.StringVar對象...我沒有找到一個好方法使它成爲一個路徑變量。

在一天

im = Image.open(self.path) 
canvas.image = ImageTk.PhotoImage(im) 
canvas.create_image(0, 0, image=canvas.image, anchor='nw') 

的到底能不能調用先前定義self.path.set('image.jpg')。我想也許有一個xy圖片列表,並做path.set(piclist[i])更改tkinter.canvas中的圖像。

+1

什麼是「不工作」是什麼意思,在「什麼是行不通的發送文件名」的句子。你有錯誤嗎?發送了錯誤的東西嗎?什麼都沒有發送? –

回答

0

我不知道你想實現什麼,爲什麼在這裏使用線程。你的代碼有一些不一致性,缺少導入語句等。因此,我簡化了它,以便我可以運行它並專注於你所指示的行。簡化版本是:

from tkinter import Tk, Canvas, StringVar, Label 
from PIL import ImageTk, Image 
from threading import Thread 

class proc(): 
    def __init__(self): 
     pass 
     # Thread.__init__(self) 

    def run(self): 
     self.root=Tk() 
     self.labelstring = StringVar() 
     self.labelstring.set('Foo') 

     self.path = StringVar() 
     self.path.set('empty.gif') 

     canvas = Canvas(self.root, width=888, height=600) 
     canvas.pack() 

     im = Image.open(self.path.get()) #<-- does not work 
     canvas.image = ImageTk.PhotoImage(im) 
     canvas.create_image(0, 0, image=canvas.image, anchor='nw') 

     label = Label(self.root,textvariable=self.labelstring) 
     label.pack() 
     self.root.mainloop() 


app = proc() 
app.run() 

集中在不工作的路線,在你的榜樣,你有:

im = Image.open(self.path) 

但你應該得到的文件的路徑如下(在我的例子) :

im = Image.open(self.path.get()) 
+0

我使用的線程能夠從「外部」更新tkinter畫布 - 我想例如更改畫布中的圖像每10秒。爲什麼我需要一個.get()在這個類裏面的文件名,而我不需要它的標籤(label = Label(self.root,textvariable = self.labelstring)) – xtlc

+0

你可以使用tkinters''after'方法每10秒執行一次,如果你真的想爲此使用它們,則不需要線程。 'Label'已經知道'self.labelstring'是'StringVar()'的一個對象,它知道調用它的'get()'方法。 PIL不知道它。它只是將一個圖像文件的路徑作爲一個字符串。 – Marcin

+0

關於線程的事情:我讀過,當嘗試更新例如畫布時,我應該使用多個線程。 – xtlc

相關問題