I am trying to create a GUI that shows your picture after you upload it. I wrote this code for it. But for some reason, it does not show the image. How can I update the root.mainloop() to show the image?
displaynumber = 0
root = tk.Tk()
f1 = ''
v = tk.IntVar()
def ShowChoice():
print(v.get())
tk.Label(root, text="""Choose method:""", justify = tk.LEFT, padx = 20).pack()
#uploading file
def selecting():
global displaynumber
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
f1 = root.filename
displaynumber = 2
print (root.filename)
# radio button
tk.Radiobutton(root, text="Select Image from Directory", padx = 20, variable=v, command=selecting, value=1).pack(anchor=tk.W)
# function for displaying image
if displaynumber > 0:
global img
img = ImageTk.PhotoImage(Image.open(f1))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both")
root.update()
elif displaynumber ==0:
pass
# root mainloop and geometry
root.geometry("1000x500")
root.mainloop()
The problem is that your if statement is not checked in mainloop
. mainloop
only updates the Tk instances that you added to root
; thus, the code never re-enters your if statement. You could replace mainloop
with your own loop that would contain the update_idletasks
and update
methods. Here is a StackOverflow answer that did a good job explaining tk.mainloop
.
You also made an error when using Image.open()
. This method takes a file and not a string, so you would need to open that file using the open
method before you use it:
with open(f1) as img_file:
img = ImageTk.PhotoImage(Image.open(f1))
Thus your code should look something like that:
displaynumber = 0
root = tk.Tk()
f1 = ''
v = tk.IntVar()
def ShowChoice():
print(v.get())
def selecting():
global displaynumber
global f1
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
f1 = root.filename
displaynumber = 2
tk.Label(root, text="""Choose method:""", justify = tk.LEFT, padx = 20).pack()
tk.Radiobutton(root, text="Select Image from Directory", padx = 20, variable=v, command=selecting, value=1).pack(anchor=tk.W)
root.geometry("1000x500")
# Your new loop
while True:
if displaynumber > 0:
global fl
with open(f1) as img_file:
img = ImageTk.PhotoImage(Image.open(f1))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both")
displaynumber = 0
elif displaynumber ==0:
pass
root.update_idletasks()
root.update()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.