I'm making some kind of cookie clicker game with Tkinter to practise my Python skills.
This is my code so far:
"""
author: Elxas866
file: BubbleClicker.py
descr.: A cookie clicker-like game
"""
from tkinter import *
from PIL import ImageTk, Image
clicks = 0
def counter():
global clicks
clicks += 1
print(clicks)
def main():
root = Tk()
root.minsize(500, 500) #pixels
root.title("Bubble Cliker")
bubble = Image.open("assets/Bubble.png")
Bubble = ImageTk.PhotoImage(bubble)
image = Button(image=Bubble, command=counter)
image.pack()
image.place(relx=0.5, rely=0.5, anchor=CENTER)
score = Label(text=clicks, font=("Arial", 25))
score.pack()
root.mainloop()
main()#call
Everything works perfectly fine, but it doesn't show my score in the label. It updates it if I print it so technically it works. But in the label it stays 0. Do you now how to fix that?
Thanks in advance!
In the counter() function, after clicks += 1, add score.config(text=score)
So the final function looks like this:
def counter():
global clicks
clicks += 1
score.config(text=score)
Also, just a suggestion: Avoid importing everything from a module.
Final function:
def counter():
global clicks
clicks += 1
score.config(text=clicks)
Correct code:
"""
author: Elxas866
file: BubbleClicker.py
descr.: A cookie clicker-like game
"""
from tkinter import *
from PIL import ImageTk, Image
clicks = 0
def counter():
global clicks
clicks += 1
score.config(text=clicks)
print(clicks)
def main():
root = Tk()
root.minsize(500, 500) #pixels
root.title("Bubble Cliker")
bubble = Image.open("assets/Bubble.png")
Bubble = ImageTk.PhotoImage(bubble)
image = Button(image=Bubble, command=counter)
image.pack()
image.place(relx=0.5, rely=0.5, anchor=CENTER)
global score
score = Label(text=clicks, font=("Arial", 25))
score.pack()
root.mainloop()
main()#call
Related
import tkinter as tk
from tkinter import *
import keyboard
import time
a = 120
root = tk.Tk()
root.state('zoomed')
root.configure(bg='white')
root.resizable(False, False)
a = 30
x = 0
def increase():
global a
a += 10
def ar():
for i in range(50):
labele1.place(x=120, y=a)
root.after(1000, increase)
c1 = Canvas(root, width=700, height=700, bg='gray95')
c1.place(x=450, y=60)
labele1 = tk.Label(c1, text='_______', font='Calibri 20')
startbutton = tk.Button(text='Başla', command=ar)
startbutton.pack()
root.mainloop()
I want to create a moving label which moves per second. Everything looks clear but it doesn't work well. I want to make a car race app but first the walls should move back and it exit the project
The idea to use root.after is correct, but the implementation is wrong. Just because you update the value of a inside a function, tkinter will not automatically update that value with its widget unless you manually ask it to. So what you can do is:
Make the label a canvas object (recommended since you will be making a game and canvas is closer to give you tools you need):
def ar():
global a
a += 10 # Increase the value of a
c1.coords('wall', [120, a]) # Change the coord of the tag 'wall'
root.after(25, ar) # Repeat this function every 25 ms
....
labele1 = tk.Label(c1, text='_______', font='Calibri 20')
c1.create_window(120, a, window=labele1, tags='wall') # Initial coords -> x=120, y=30
Change the location of the label using place_configure:
def ar():
global a
a += 10 # Increase the value of a
labele1.place_configure(y=a)
root.after(25, ar) # Repeat this function every 25 ms
....
labele1 = tk.Label(c1, text='_______', font='Calibri 20')
labele1.place(x=120, y=a)
Plus checking frame size and decreasing functions.
the main problem was a minor bug which you should change in line 37.
import tkinter as tk
from tkinter import *
import keyboard
import time
a = 120
root = tk.Tk()
root.state('zoomed')
root.configure(bg='white')
root.resizable(False, False)
a = 30
x = 0
moving_rate = 10
max_y = 600
min_y = 30
flag_mov_func= 1
def moving_func(): #increase or decrease function
global a
global flag_mov_func
if flag_mov_func :
a += moving_rate
if a + moving_rate == max_y: #simple logic bouncing if it ends
flag_mov_func=0
elif flag_mov_func==0 :
a -= moving_rate
if a - moving_rate == min_y:
flag_mov_func=1
def ar():
moving_func()
labele1.place(x=120, y=a)
root.after(1000, ar)
flag_is_called=1
def button1(): #new update on code to make the button work once.
global flag_is_called
if flag_is_called:
flag_is_called=0
ar()
c1 = Canvas(root, width=700, height=700, bg='gray95')
c1.place(x=450, y=60)
labele1 = tk.Label(c1, text='_______', font='Calibri 20')
startbutton = tk.Button(text='Başla', command=button1)
startbutton.pack()
root.mainloop()
This is a photo slideshow code its just a skeleton I want use buttons to start or stop the code from slide show.
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
# This here is to adjust window
root=tk.Tk()
root.geometry("200x200")
# loading the images
img=ImageTk.PhotoImage(Image.open("photo1.png"))
img2=ImageTk.PhotoImage(Image.open("photo2.png"))
img3=ImageTk.PhotoImage(Image.open("photo3.png"))
img4=ImageTk.PhotoImage(Image.open("photo4.png"))
l=Label()
l.pack()
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x+1
root.after(2000, move)
# calling the function please refer the indents
btn_1 = Button(root, text="start", command=move)
btn_1.pack()
btn_2=Button(root,text="start", command=pause))
btn_2.pack()
root.mainloop()
Here's runnable code that illustrates how to do it. It uses several global variables to keep track of the current state of the slide show that the various functions use to determine what needs to be be done.
It simplies the logic you had for determining the next image to display by adding one to then current image index and the applying the modulo % the number of images in show which forces the index back to 0 whenever it exceeds the number of image that there are — which can all be done with a single statement: cur_img = (cur_img+1) % len(slides).
You could get rid of the most of the globals by defining a SlideShow class that encapsulated the state variables and defined the related functions that manipulate them.
from pathlib import Path
from PIL import Image
from PIL import ImageTk
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
after_id = None
cur_img = 0
paused = True
image_folder = Path('./photos')
slides = [ImageTk.PhotoImage(Image.open(filename))
for filename in image_folder.glob('*.png')]
def slide_show():
"""Change to next image (wraps around)."""
global after_id, cur_img, paused
if not paused:
cur_img = (cur_img+1) % len(slides)
lbl.config(image=slides[cur_img])
after_id = root.after(2000, slide_show)
def start():
global after_id, cur_img, paused
paused = False
if after_id: # Already started?
root.after_cancel(after_id)
after_id = None
slide_show()
def pause():
global after_id, cur_img, paused
paused = True
lbl = tk.Label(image=slides[cur_img])
lbl.pack()
btn_1 = tk.Button(root, text="start", command=start)
btn_1.pack()
btn_2 = tk.Button(root, text="pause", command=pause)
btn_2.pack()
root.mainloop()
I want to change the image of the one labels in time with 2 other images but it immideatly skipts to the last one. Any suggestions?
I have tried using time.sleep incase it might happen so fast that before i could notice but it didnt work.
import tkinter
from tkinter import *
from PIL import Image , ImageTk
import time
window = tkinter.Tk()
window.geometry("500x500")
window.title("Pomodoro Timer")
window.image_1 = ImageTk.PhotoImage(Image.open("1.jpg"))
window.image_2 = ImageTk.PhotoImage(Image.open("2.jpg"))
window.image_3 = ImageTk.PhotoImage(Image.open("3.jpg"))
lbl_1 = tkinter.Label(window, image=window.image_1)
lbl_1.place(x=150,y=100)
lbl_2 = tkinter.Label(window, image=window.image_2)
lbl_2.place(x=200,y=100)
def display_numbers():
lbl_1
lbl_2
display_numbers()
def clicked():
i=1
while i<3:
if i==1:
lbl_1.configure(image=window.image_2)
time.sleep(0.91)
i += 1
elif i==2:
lbl_1.configure(image=window.image_3)
time.sleep(0.91)
i += 1
btn = tkinter.Button(window, text="Start", command=clicked)
btn.place(x=200,y=450,width=100)
window.mainloop()
I am currently coding a little Python script for a colleague of mine which should give the framework for his PhD defense challenge, e.g. little tasks and questions he has to answer. The script itself should guide him through his challenges and give those tasks, introductions, etc.
I am currently using Tkinter for that purpose. Principally, I want to have a canvas/part of the screen, where text and introductions pop up like in the example shown below.
import Tkinter as tk
import time
global_delay =150
counter = 0
delay = global_delay
def display_text():
global num_letters
global global_text
global label
text = global_text[counter]
num_letters = len(text) - 1
old_text = label.cget("text")+'\n'
def display():
global num_letters
global counter
global global_delay
global delay
if delay == 0:
user_text = ''
com_text = ' '
else:
user_text = 'user#hlrdbb4 ~ '
com_text = ''
print_text = old_text + user_text + str(text[1:len(text) - num_letters])+(num_letters+50-len(text))*' ' + com_text
label.config(text=print_text)
label.config(font=("Courier", 30))
num_letters-=1
if num_letters>=0:
label.after(delay, display)
elif counter<len(global_text)-1:
counter += 1
if global_text[counter][0] == 'o':
delay = 0
if global_text[counter][0] == 'i':
delay = global_delay
label.after(global_delay*10, display_text)
display()
root = tk.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
root.title("PhD")
label = tk.Label(root, fg="green", bg='black', height=h, width=w, anchor=tk.NW)
label.pack()
global_text=['icd E:\dbb\ ','oChange directory to E:\dbb\ ','iget_PhD.exe','oError file not found','iget_PhD.exe','oError file not found','iget_PhD.exe','oExecuting get_PhD.exe','oHere are your introductions...']
display_text()
root.mainloop()
The other side of the GUI should display the corresponding minigames, e.g. a dynamically changing noise plot for which he has to put in some numbers to see a decent signal. As you can see I am currently using the after-method at the moment to display the text, but I can't figure out, how to incorporate such games or how the script could wait for his (keyboard) input to continue.
Could anyone help me here a bit?
You could bind a keyboard input (in this case enter) or a tkinter button, to use the input of an Entry widget. You execute a function with it (in this case callback). You continue your program if you get the desired input.
import tkinter as tk
root = tk.Tk()
e = tk.Entry(root)
e.pack()
def callback(*args):
print (e.get())
e.bind("<Return>",callback)
root.mainloop()
Some good reading material and extra explanation:
Tkinter Confirmation buttons and game GUI (splice(?))
A hoy hoy, I would like to know how I can take a parameter in a function and make it a label and also then .grid_forget() label again (Answer is on a "Restart?" window). I'm making a currency converter from scratch and my code is terrible.
Take a look at one of my Tkinter programs. Look at where it says counter. That is the variable. The Tkinter website is also so helpful! Good luck!
from tkinter import *
import sys
root = Tk()
root.geometry("480x320")
root.title("School Days Left!")
global counter
counter = 30
def upClick():
global counter
counter += 1
def downClick():
global counter
counter -= 1
mButton1.config(text = counter, borderwidth = 0, highlightthickness=0, relief='ridge', pady = "100")
mButton1 = Button(text = counter, command = downClick, height = 4000, width = 320, font = ("Monospace", 200))
mButton1.pack()
root.mainloop()