How do i pause my code before displaying the label - python

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.

Related

Images not getting applied on the button in Tkinter

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

Adding Windows to Buttons on Tkinter GUI

I'm new to Python, I'm trying to add widgets in an window which can be used when we click on an button when in Tkinter GUI.
I'm unable to add an window into the GUI button and I'm doubtful about the Code which can be Implemented as well. I hope I could get some inputs on this.
I'm running on IDLE 3.6.3.I would be grateful if someone could point out the additions that could be made and the changes in the current code.
ConnectLogo=PhotoImage(file="Connect.png")
Connect = Button(win,image=ConnectLogo,text = "Connect", font = myFont,height =100 , width = 100,compound=TOP,bg = "orange")
Connect.grid(row=3,column=1,padx=50,pady=40)
FrequencyLogo=PhotoImage(file="Frequency.png")
Frequency = Button(win,image=FrequencyLogo, text = "Frequency", font = myFont, height = 100, width =180,compound=TOP,bg = "Yellow")
Frequency.grid(row=3,column=2,padx=10)
MaskLogo=PhotoImage(file="Mask.gif")
Mask = Button(win,image=MaskLogo, text = "Mask", font = myFont, height = 100, width =180,compound=TOP,bg = "yellow")
Mask.grid(row=6,column=2,padx=10)
You can make a function, which will implement TopLevel.
This creates a new window into which you can add widgets, add them inside the function.Inside the function you root becomes window
from tkinter import *
root = Tk()
def new_window():
window = TopLevel(root)
...widgets like label, entry etc
label = Label(window,....)
btn = Button(...., command = new_window)
btn.pack()...(anything)

How to move tkinter windows using python after it has been created?

I am looking to move a tkinter window to different x and y coordinates after it has been created. For example 5 seconds after the window has been created move it to
x=??? and y=???.
from tkinter import*
root = Tk()
root.title("lol")
root.geometry("300x300")
photo = PhotoImage(file="pepe.gif")
label = Label(image=photo).place(x=10, y=10)
root.mainloop()
The above code is just an example, how does it need to be modified to move by itself?
This example will show you how to reset the root geometry that controls the position of the window on screen; clicking on the image will toggle the locationof the window.
from tkinter import *
def move_me(idx=[0]): # <- creates a closure for the index of the location strings
loc = ["300x300+200+200", "300x300+300+300"]
root.geometry(loc[idx[0]]) # <-- reset the geometry
idx[0] = (idx[0]+1) % 2 # <-- toggles the index between 0 and 1
root = Tk()
root.title("lol")
root.geometry("300x300-100+100")
photo = PhotoImage(file="pepe.gif")
button = Button(root, image=photo, command=move_me)
button.place(x=10, y=10)
root.mainloop()
[edit] with auto repeat moving the window.
(attention, you have challenging game to catch the window to close it)
from tkinter import *
import random
def move_me():
x, y = str(random.randrange(800)), str(random.randrange(800))
loc = "300x300+" + x + '+' + y
root.geometry(loc)
root.after(500, move_me) # <-- auto call to move_me again every 1/2 second
root = Tk()
root.title("lol")
root.geometry("300x300+100+100")
photo = PhotoImage(file="pepe.gif")
label = Label(root, image=photo)
label.place(x=10, y=10)
move_me() # <-- call to move_me
root.mainloop()

Why is my image appearing on the wrong window in Tkinter?

So I am trying to make a text-based game, but also want to incorporate images into it, I have a main menu, a window that is always open, and then a game window, that should have the image in, but for some reason, it appears in the menu window instead. Has anyone got any idea why?
def menu():
master = Tk()
master.geometry("350x300")
master.wm_iconbitmap("zombie.ico")
master.configure(background = '#484a2c')
master.title("Menu")
def game():
master = Tk()
master.geometry("800x500")
master.title("Game")
master.wm_iconbitmap("zombie.ico")
master.configure(background = '#484a2c')
image = PhotoImage(file="Kitchenimage.gif")
label5 = Label(image=image)
label5.image = image
label5.pack()
label = Label(master, text = "Zombie Mansion", background = '#484a2c',
font = ("AR CHRISTY", 30))
label.pack()
b = Button(master,text = "Play Game", height = 1, width = 10)
b.config(background = '#484a2c', activebackground = '#484a2c', font =
("AR CHRISTY", 14), command = get_username)
b.place(x = 120, y = 70)
mainloop()
"Why is my image appearing on the wrong window in Tkinter?"
Assuming you have another instance of Tk as what you refer to as main menu somewhere in your code that you're not showing us like:
main = Tk()
in addition to master = Tk() in your game method, then it's because when you instantiate widgets without passing a parent widget explicitly like in:
label5 = Label(image=image)
then the widget's parent defaults to the Tk instance whose mainloop is being run, in above case supposedly main's. By default widgets are shown under their parents, hence the reason.
Pass parent explicitly like:
label5 = Label(master=main, image=image)
or
label5 = Label(master, image=image)
In most cases, if not all cases, you shouldn't have multiple instances of Tk. If you require additional windows, please use Toplevel widget.

Python Tkinter Moving images on buttonpress

I am trying to write a Tkinter code where it image, which looks like rain will start to move, if button called "Rain" is pressed.
I can not yet tell how the image move part works, but the problem is that when I click on the "Rain" button, it writes -> "Rain" like it should but no image appears on Canvas.
Another interesting thing is that when i take
Here is my code:
root = Tk()
#Create the canvas
canvas = Canvas(width=1000, height=1000)
canvas.pack()
#This is the part that does not work
#Nothing appears when this function is called
def Rain():
image3 = "Drops.png"
drops = PhotoImage(file = image3)
drops_background = canvas1.create_image(100, 100, image=drops)
while True:
canvas1.move(drops_background, 10, 10)
print("Rain")
#Adding a button and making it to use function "Rain"
frame = Frame(root)
frame.pack()
button1 = Button(frame, text = "Rain", command = Rain, fg = "red" ).pack(side = LEFT)
root.mainloop()
Another interesting thing is that if I place this part out of the function it starts working.
image3 = "Drops.png"
drops = PhotoImage(file = image3)
drops_background = canvas1.create_image(100, 100, image=drops)
If anyone could tell me what is wrong here or at least point me in the right direction that would help me out a lot.
There is issue in PhotoImage (or rather in PIL and Pillow module) - PhotoImage must be assigned to global variable.
If PhotoImage is assigned to local variable then Garbage Collector remove it from memory.
My full working example with after
import Tkinter as tk
import random
# --- globals ---
drops_background = None
drops = None
# --- functions ---
def rain():
global drops_background
global drops
filename = "Drops.png"
drops = tk.PhotoImage(file=filename) # there is some error in PhotoImage - it have to be assigned to global variable
drops_background = canvas.create_image(100, 100, image=drops)
# move after 250ms
root.after(250, move) # 250ms = 0.25s
def move():
global drops_background
# TODO: calculate new position
x = random.randint(-10, 10)
y = random.randint(-10, 10)
# move object
canvas.move(drops_background, x, y)
# repeat move after 250ms
root.after(250, move) # 250ms = 0.25s
# --- main ----
root = tk.Tk()
#Create the canvas
canvas = tk.Canvas(root, width=1000, height=1000)
canvas.pack()
#This is the part that does not work
#Nothing appears when this function is called
#Adding a button and making it to use function "Rain"
frame = tk.Frame(root)
frame.pack()
button1 = tk.Button(frame, text="Rain", command=rain, fg="red" )
button1.pack(side=tk.LEFT)
root.mainloop()
after add function and time to its list and mainloop run function from this list after given time.
after expects function name without ()

Categories