tkinter not executing function properly [duplicate] - python

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
I'm having a weird issue with the tkinter script below. If the outcommented lines are executed, it is showing the image like intended. When I call the function instead, it doesn't. The main window i opened and nothing else happens. 'Function called' is being printed in the Shell though. Am I missing something basic about tkinter and/or functions here? I found some reports about weird behavior with IDLE which I'm using as well, could that be the reason?
Yesterday I had some issues because I called the file tkinter.py, same as the module but in a different folder. Like a few more persons, that resulted in problems opening the scripts with IDLE. I wrote a new file with the code below and the problem persisted.
from tkinter import *
import tkinter as tk
from PIL import Image, ImageTk
from pathlib import Path
window = Tk()
window.title('xy')
window.geometry('600x400')
path = Path("C:/Python/png/")
def function_a():
print('function called')
img = Image.open(str(path)+'\\'+'pic'+'.png')
img = img.resize((300,200), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
background_label = tk.Label(window, image=img)
background_label.pack()
function_a()
##img = Image.open(str(path)+'\\'+'pic'+'.png')
##img = img.resize((300,200), Image.ANTIALIAS)
##img = ImageTk.PhotoImage(img)
##background_label = tk.Label(window, image=img)
##background_label.pack()
window.mainloop

The photo img gets removed by garbage collection because it is a local variable.
To fix this add background_label.img = img at the end of the function, this stops the image from being removed by garbage collection.

Related

Image not showing in tkinter button [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 3 months ago.
I created a button with an image in Tkinter, but the image isn't showing, i can just see a blank space in the button. Maybe my OS is the problem. I have Linux Mint 21 Xfce Edition.
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import dialog
from tkinter import *
from PIL import ImageTk, Image
from modules import fonts, buttons
import shutil
import os
virusscan_win = Tk()
virusscan_win.title("Virus scan")
virusscan_win.geometry('400x200+60+60')
virusscan_win.configure(background="white")
Message(text="The virus scanner gives them the ability to scan files, folders or their system for viruses and remove threats automatically.", width=250, font=fonts.sansserif_small, background = "white").place(x=10, y=10)
safe_image=PhotoImage(file='./media/button.png')
Button(master=virusscan_win, image=safe_image, text="Scan file").place(x=10, y=90)
Can anyone explain, what was wrong with my code? I already checked, is the file in the correct folder. the debugger also shows nothing.
Python is notorious for aggressively garbage collecting image references, which leads to them being destroyed before the UI gets drawn. Something like this should work for getting an image onto a Button
from PIL import Image, ImageTk
from pathlib import Path
img_path = Path('C:/<path>/<to>/media/button.png') # use the full path to your img file
with Image.open(img_path) as img: # open the image file
img_tk = ImageTk.PhotoImage(img) # get the image as a Tk object
button = Button(virusscan_win, image=img_tk) # add image to button
Note that if your image is the wrong size for your button, you can resize it like so
img_tk = ImageTk.PhotoImage(img.resize(32, 32)) # or whatever size you need

not displaying image in Tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Tkinter PIL image not displaying inside of a function
(1 answer)
Closed 2 years ago.
So I'm experimenting With Tkinter message boxes And I'm trying to insert an image in my toplevel window>
from tkinter import*
from tkinter import messagebox
root = Tk()
root.title('Hi')
root.iconbitmap('C:/Users/davids/Downloads/i2.ico')
e = Entry(root,borderwidth=8,width=35)
top = Toplevel()
def popup():
mg = messagebox.askyesno("Warning", "Click yes/No.")
if mg == True:
top = Toplevel()
top.geometry('1200x1200')
b= Label(top, text="hi")
b.pack()
image = PhotoImage(file="path")
Label(root, image=image).pack()
Button(root,text="Ask question", command=popup).pack()
root.mainloop()
However when I run this code nothing shows. There isn't an error so I can't see what I'm doing wrong. Only the text is displayed. I've tried adding root. but that still doesn't fix it. Please note that I do know that it is easier to use PIL however my new operating system won't install it for some reason so I'm trying to find a way without Pillow. Any idea what is happening?

Tkinter: Pyimage is not working in a Function [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 5 years ago.
I was trying to code a small window in a program that is giving you feedback about your statistics in the game. The output is working fine, but the image i tried to edit is not working. I tried to define the image global, i tried to take the direct path, i tried to change the suffix of the picture i want to edit (right now it's a .gif -file) but nothing is working. Whats wrong? What is my mistake?
import tkinter
def blackhole():
Black=tkinter.Tk()
Black.title("BlackHole")
schrift=tkinter.Label(Black,text="BlackHole: Game got reseted!")
schrift.pack()
Medal=tkinter.Label(Black,text="Congretulation! You earn the Bronze Medal!")
Medal.pack()
knopf=tkinter.Button(Black,text="Ok",command=submit)
knopf.pack()
canvas = tkinter.Canvas(Black, width=250, height=250)
canvas.pack()
tk_img = tkinter.PhotoImage(file = '/Users/Hannes/Desktop/Klickbot/b.gif')
canvas.create_image(150, 150, image=tk_img)
To include images with Tkinter you should use Pillow (PIL).
https://python-pillow.org/
Run pip install Pillow from the terminal to install.
Sample usage:
from PIL import ImageTk, Image
img = ImageTk.PhotoImage(Image.open("logo.png"))
panel = Label(root, image=self.img)
panel.pack(side="top", fill="both", expand="yes")

How to load an image into a python 3.4 tkinter window?

I've spent some time looking online and so far haven't found anything that answers this without using PIL, which i can't get to work is there another way to do this simply?
tkinter has a PhotoImage class which can be used to display GIF images. If you want other formats (other than the rather outdated PGM/PPM formats) you'll need to use something like PIL or Pillow.
import Tkinter as tk
root = tk.Tk()
image = tk.PhotoImage(file="myfile.gif")
label = tk.Label(image=image)
label.pack()
root.mainloop()
It's important to note that if you move this code into a function, you may have problems. The above code works because it runs in the global scope. With a function the image object may get garbage-collected when the function exits, which will cause the label to appear blank.
There's an easy workaround (save a persistent reference to the image object), but the point of the above code is to show the simplest code possible.
For more information see this web page: Why do my Tkinter images not appear?
You can use PIL library which available for python 3.
First, you need to install PIL using this command (using pip):
pip install pillow
then:
`from tkinter import *`
from PIL import Image, ImageTk
`class Window(Frame):`
`def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=1)
load = Image.open("parrot.jpg")
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=0, y=0)`
Luke, this is too late , however may help others. Your image has to be in the same sub directory with .py script. You can also type './imageFileName.png'

How do I update images on a Tkinter Canvas?

I'm trying to make a script which will enable me to dynamically update an image object and then post the updated image to a Tkinter Canvas widget. The code here is prototype code, just to get the basics down. The aim here is to put a blue pixel on the image being displayed by the canvas, at the click location.
Something very strange is going on here. I'm using the Wing IDE, and if I run this code through the debugger, with a breakpoint at any line in the woohoo function, and then continue execution after hitting the breakpoint, the code works exactly as expected- putting a blue pixel on the image. If I run the code normally, or through the debugger with no breakpoints, the image is never updated. This leads me to the conclusion that there is some internal wizardry going on which I haven't got much hope of understanding without aid.
I'd really like to know the best way to go about this (or any way, I guess), and if someone could explain to me what's going on under the hood that'd be really cool. Thanks.
from Tkinter import *
from PIL import Image, ImageTk
def woohoo(event):
original.putpixel((event.x,event.y),(0,0,255))
newpic = ImageTk.PhotoImage(original)
c.create_image((0,0),image=newpic, anchor="nw")
main = Tk()
c = Canvas(main, width=300, height=300)
main.geometry("300x300+0+0")
c.pack()
original = Image.open("asc.bmp")
picture = ImageTk.PhotoImage(original)
c.create_image((0,0),image=picture, anchor="nw")
c.bind("<Button-1>", woohoo)
main.mainloop()
My guess is, you're creating a new image in a function. The reference to the image is a local variable. When the function exits, the reference is garbage collected which causes the new image to be destroyed. Most likely, running interactively causes the garbage collector to run differently (perhaps more lazily?)
Changed a little of the other post to work with Python 3+ :
from tkinter import *
def stuff(event):
global picture3
picture3 = PhotoImage(file='picture2.png')
c.itemconfigure(picture2, image = picture3)
main = Tk()
c = Canvas(main, width=300, height=300)
c.pack()
picture = PhotoImage(file='picture1.png')
picture2 = c.create_image(150,150,image=picture)
c.bind("<Button-1>", stuff)
main.mainloop()
try it like this:
from Tkinter import *
from PIL import Image, ImageTk
def woohoo(event):
global picture #
original.putpixel((event.x,event.y),(0,0,255))
picture = ImageTk.PhotoImage(original)#
c.itemconfigure(myimg, image=picture)#
main = Tk()
c = Canvas(main, width=300, height=300)
main.geometry("300x300+0+0")
c.pack()
original = Image.open("asc.bmp")
picture = ImageTk.PhotoImage(original)
myimg = c.create_image((0,0),image=picture, anchor="nw")#
c.bind("<Button-1>", woohoo)
main.mainloop()

Categories

Resources