The following project is supposed to show a message when clicking a certain colored button. But, whenever I execute the program it shows blank(white) buttons in the correct alignment, etc. Due to some reason the images are not loaded.
In future, I plan to add different images hence testing with colored image created in Paint and not in-built commands to show the color.
I will add the result below after the code.
Edit: All images are 100x100 pixels created in Microsoft Paint.I have tried other modules like PIL but to no avail.
# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module
# initialising tkinter
class window(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
# initialising tkinter
# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window
# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
# colours
# image
red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"
# image
# creating a button function
def create_button(x,y,color,color2,picture):
click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
click.image = PhotoImage(picture)
click.grid( row = x, column = y)
# creating a button function
create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)
# starting the widget
root.mainloop()
# starting the widget
There are two issues in your code:
You passed filename to PhotoImage() without using file keyword: PhotoImage(picture) should be PhotoImage(file=picture)
You did not keep the reference of the image assigned to button, but another instance of image
Below is the updated create_button() function that fixes the issues:
def create_button(x, y, color, color2, picture):
image = PhotoImage(file=picture)
click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
click.image = image
click.grid(row=x, column=y)
For adding image in Button you have not use appropriate keywords.
Here is a simple example for you to add image in button
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = "C:\Gfg\circle.png")
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !', image = photo).pack(side = TOP)
root.mainloop()
I think it may help you
Related
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 10 months ago.
I was trying to show the image when I clicked the button however it failed( the program does not report an error but the image is still not displayed). I'm sure I put the right path to the picture. This is code
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command=def_btn1)
btn1.pack()
window = tk.mainloop()
I want when I click the button the image will show in the program. Thank you!
You need to add lbl2.image = test for the image to not be destroyed by tkinter, you new code should be this -
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk() # You might want to move this line below your functions, with the other global variables
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.image = test # You need to have this line for it to work, otherwise it is getting rid of the image. the varibale after the '=' must be the same as the one calling "ImageTk.PhotoImage"
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command= lambda : def_btn1()) # adding 'lambda :' stops the function from running straight away, it will only run if the button is pressed
btn1.pack()
window = tk.mainloop()
I'm trying to put a background image in my tkinter project, but despite of several attempts it's simply not showing up.
Here is the code:
import tkinter
from PIL import ImageTk,Image
show_screen = tkinter.Tk()
show_screen.geometry('900x900')
show_screen.title("LEARNTECH OPE")
img_show = Image.open("C:\PYTHON IDE\RemoteProctoring_Featured.png")
show_image = ImageTk.PhotoImage(img_show)
show_label = tkinter.Label(show_screen,font=("Arial Bold",10),fg="blue",
text="FILL THE NECESSARY DETAILS GIVEN BELOW")
show_label.place(x=600,y=0)
enter_field = tkinter.Entry(show_screen,width=50)
enter_field.place(x=600,y=200)
def clicked():
ref = "Welcome" + enter_field.get()
show_label.configure(text=ref)
show_button = tkinter.Button(show_screen,text="CLICK TO EXIT",
fg="green",command=clicked).place(x=600,y=400)
show_screen.mainloop()
As I said in a comment, images can only be displayed as part of some tkinter widget. Below is an example of doing that by putting the image in a Label. I also added code to resize the image to fill the window (aka "screen" in your code).
import tkinter
from PIL import ImageTk, Image
WIDTH, HEIGHT = 900, 900
IMG_PATH = r"C:\PYTHON IDE\RemoteProctoring_Featured.png" # Note 'r' prefix.
show_screen = tkinter.Tk()
show_screen.geometry('{}x{}'.format(WIDTH, HEIGHT))
show_screen.title("LEARNTECH OPE")
# Place background image on a Label widget.
tmp_img = Image.open(IMG_PATH).resize((WIDTH, HEIGHT), Image.ANTIALIAS)
bkg_img = ImageTk.PhotoImage(tmp_img)
bkg_label = tkinter.Label(show_screen, image=bkg_img)
bkg_label.img = bkg_img # Keep a reference in case this code put is in a function.
bkg_label.place(relx=0.5, rely=0.5, anchor='center') # Place in center of window.
enter_field = tkinter.Entry(show_screen,width=50)
enter_field.place(x=600,y=200)
show_label = tkinter.Label(show_screen,font=("Arial Bold",10),fg="blue",
text="FILL THE NECESSARY DETAILS GIVEN BELOW")
show_label.place(x=600,y=0)
def clicked():
ref = "Welcome " + enter_field.get()
show_label.configure(text=ref)
show_button = tkinter.Button(show_screen,text="CLICK TO EXIT",
fg="green",command=clicked)
show_button.place(x=600,y=400)
show_screen.mainloop()
In my code, I am trying to make a loading screen for a frogger game but for some reason I am encountering a problem where I display a picture and then do the .sleep function before displaying a label over the top of it however it displays both of them at the same time it just runs the code 1 second after it should, can anyone help?
Here is my code below:
from tkinter import *
import tkinter as tk
import time
window = Tk()
window.geometry("1300x899")
LoadingScreen = PhotoImage(file = "FroggerLoad.gif")
Loading = Label(master = window, image = LoadingScreen)
Loading.pack()
Loading.place(x = 65, y = 0)
time.sleep(1)
FroggerDisplay = Label(master = window, font ("ComicSans",100,"bold"),text = "Frogger")
FroggerDisplay.pack()
FroggerDisplay.place(x = 500, y = 300)
window.mainloop()
When you use time.sleep(1) before starting the window.mainloop(), the window is created only after 1 second, and the FroggerDisplay label will be created at the same time with it. So, you can't use time.sleep(seconds) now.However, you can use window.after(ms, func) method, and place into the function all the code between time.sleep(1) and window.mainloop(). Note, that unlike the time.sleep(seconds) you must give the time to window.after (the first argument) as milliseconds.Here is the edited code:
from tkinter import *
def create_fd_label():
frogger_display = Label(root, font=("ComicSans", 100, "bold"), text="Frogger") # create a label to display
frogger_display.place(x=500, y=300) # place the label for frogger display
root = Tk() # create the root window
root.geometry("1300x899") # set the root window's size
loading_screen = PhotoImage(file="FroggerLoad.gif") # create the "Loading" image
loading = Label(root, image=loading_screen) # create the label with the "Loading" image
loading.place(x=65, y=0) # place the label for loading screen
root.after(1000, create_fd_label) # root.after(ms, func)
root.mainloop() # start the root window's mainloop
PS: 1) Why do you use .pack(...) and then .place(...) methods at the same time - the first one (.pack(...) here) will be ignored by Tkinter.
2) It's better to use a Canvas widget for creating a game - unlike labels it supports transparency and simpler to use. For example:
from tkinter import *
root = Tk() # create the root window
root.geometry("1300x899") # set the root window's size
canv = Canvas(root) # create the Canvas widget
canv.pack(fill=BOTH, expand=YES) # and pack it on the screen
loading_screen = PhotoImage(file="FroggerLoad.gif") # open the "Loading" image
canv.create_image((65, 0), image=loading_screen) # create it on the Canvas
root.after(1000, lambda: canv.create_text((500, 300),
font=("ComicSans", 100, "bold"),
text="Frogger")) # root.after(ms, func)
root.mainloop() # start the root window's mainloop
Note: you might need to change coords with Canvas.
I am trying to make tk buttons look better by adding a button background. The issue is, I can use an image or text, but not both, for a tk button.
How can you have both?
This is what I have tried:
from tkinter import *
from PIL import Image, ImageTk
print("I ran")
master = Tk()
canvas_width = 800
canvas_height = 400
window = Canvas(master,
width=canvas_width,
height=canvas_height)
img = Image.open("images/button_black.png").resize((80,40))
ph_image = ImageTk.PhotoImage(img)
l = Label(master, text='Button', image=ph_image, compound=CENTER, fg="white")
l.pack(side=LEFT)
button = Button ( master, image=l)
window.pack()
mainloop()
To use both an image and text you must set the compound option. From the canonical documentation:
Specifies if the widget should display text and bitmaps/images at the same time, and if so, where the bitmap/image should be placed relative to the text. Must be one of the values none, bottom, top, left, right, or center. For example, the (default) value none specifies that the bitmap or image should (if defined) be displayed instead of the text, the value left specifies that the bitmap or image should be displayed to the left of the text, and the value center specifies that the bitmap or image should be displayed on top of the text.
Example:
The following example uses this image:
The program renders like this when using compound="center":
import tkinter as tk
image_data = '''
R0lGODdhyABkAKIAAAAAAP8mAP/7AP///wAAAAAAAAAAAAAAACH5BAkAAAQALAA
AAADIAGQAAAP/KLrc/jDKSau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987/
/AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOl
wTu+Lx+z+8H6jZ+goOEg4AnhYmKi3yHHIyQkZGOE5KWl5CUCpicnYx1nqGihHCj
pqd+a6irrHlnrbCwY7G0sl+1uKxeubyoXL3AplnBxMJWxciex8nMmFXN0JJU0dS
ZUtXYiVPZ3ILb3eB63+Hk4+Tg5ufc6erY0+3Zz/Du8vPQV/bRw/nFv/zAu/7lAi
Ow1qyCq14hFKVqobM3Dj/RiUhKE0U8miIUzIihNh3HEPo+toglsqTJkyhTqlzJs
qXLlzBjypxJs6bNmzhz6tzJs6fPn0CDCh1KtKjRo0iTKlWZAAA7
'''
root = tk.Tk()
image = tk.PhotoImage(data=image_data)
label = tk.Button(root, image=image, text="Hello, world", compound="center")
label.pack(padx=20, pady=20)
root.mainloop()
I am trying to implement a button that has transparency using PIL and reading a PNG with transparency. I've followed all the tips I can find, but the button still shows up without transparency.
Screenshot of button in GIMP
Screenshot of Python output
Here is the code:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.resizable(width=FALSE, height = FALSE)
global background, redbutton, rb1
rb1 =ImageTk.PhotoImage(file="test.png")
#confirm the png file is correct format
im = Image.open("test.png")
print im.mode
bg = PhotoImage(file = "background.gif")
GameWin = Canvas(root, bd = 2, height = 600, width = 450)
GameWin.create_image(0,0, image = bg, anchor = NW)
rb = Button(GameWin, bd=0, image=rb1)
# create a window in the canvas for the button
rb_win = GameWin.create_window(10, 10, anchor=NW, window=rb)
GameWin.pack()
root.mainloop()
Putting a window onto the canvas overwrites the background image. If I create_image in the canvas, I can correctly put the image of the button on the canvas (with transparency), but not an actual Button widget. My next step is to learn how to have the image react to mouseclicks so I can emulate some basic Button functionality.