Reputation: 2333
I'm starting with GUI in Python and Tkinter and want to make a small window that load an image from a file and show the path of the file and also de image. Until now, I've got my window and the button to pick the image (tkinter.filedialog.askopenfilename) but I'm trying to update the Entry that is supposed to show the path using a tkinter.StringVar. The value of the StringVar is changing, but not the value shown in the Entry.
Frame Code:
import tkinter as tk
import tkinter.filedialog as tkf
class ImageViewer(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master.title("Image Viewer")
self.drawButtons()
self.grid()
def drawButtons(self):
self.lblfilename = tk.Label(self, text="Image: ")
self.lblfilename.grid(padx=1, column=0, row=0, sticky=tk.N+tk.E+tk.S+tk.W)
self.eText = tk.StringVar()
self.eText.set("")
self.filenametext = tk.Entry(self, background='#fff', width=65, textvariable=self.eText)
self.filenametext.grid(padx=10, column=1, row=0, columnspan=2, sticky=tk.N+tk.E+tk.S+tk.W)
self.pickerbut = tk.Button(self, text="Load", command=self.picker)
self.pickerbut.grid(column=3, row=0, sticky=tk.N + tk.S + tk.W)
self.image = tk.Canvas(self, height=480, width=640)
self.image.grid(padx=10, pady=5, column=0, row=1, columnspan=4, rowspan=3)
self.cancelbut = tk.Button(self, text="Exit", command=self.cancel)
self.cancelbut.grid(column=3, row=4, sticky=tk.N + tk.W + tk.S)
def picker(self):
self.imgpicker = tkf.askopenfilename(parent=self)
self.eText.set(self.imgpicker)
print(self.eText.get())
def cancel(self):
self.master.destroy()
main:
if __name__ == "__main__":
imageviewerbutton = tk.Tk()
imageviewerbutton.geometry('660x550+100+90')
ImageViewer(imageviewerbutton)
imageviewerbutton.mainloop()
When I print the value of self.eText with self.eText.get(), it show the correct image path, but my Entry remain empty.
In my opinion, it is any kind of problem when bindind the StringVar and the Entry, although I've already search on internet and try everything that came to my mind, I didn't found a solution.
Can someone give me a hint?
Upvotes: 0
Views: 1109
Reputation: 386342
I don't have a python3 instance where I can test this, but it seems to work OK on python 2.7.
Are you aware you don't need to use a StringVar
with an entry widget? In my opinion you almost never need one. You can get and set the value of the entry without it.
For example:
self.imgpicker = tkf.askopenfilename(parent=self)
self.filenametext.delete(0, "end")
self.filenametext.insert(0, self.imgpicker)
Upvotes: 0