.after() Causing Tkinter Window To Freeze - python

I'm making a cookie clicker game in tkinter. I'm trying to program an auto click function for the player to buy that clicks the cookie every ten seconds. I attempted to use the .after() method, however this freezes the program. To clarify, the other functions such as the user clicking the cookie need to still be functional whilst the auto click runs in the background.
Here is the auto click function:
def autoclick():
def tensecs():
while True:
global clicks
clicks = clicks + 1
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
shop_window.after(1000, tensecs)
Here is the full program:
from Tkinter import *
from Tkinter import Canvas
import ttk
import time
window1 = Tk()
window1.title("Cookie Clicker")
window1.config(background="dodger blue")
window1.geometry("254x390")
clicks = 0
class FlashableLabel(Label):
def flash(self, count):
bg = self.cget('background')
fg = self.cget('foreground')
self.configure(background=fg, foreground=bg)
count += 1
if count < 1000:
self.after(250, self.flash, count)
def cookie_clicks(event):
global clicks
clicks = clicks + 1
pb.step(10)
print("{0}".format(clicks))
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
def about_btn():
about_window = Toplevel(window1)
about_window.overrideredirect(1)
about_window.geometry("230x150+15+50")
about_window.config(background="snow2")
photo4 = PhotoImage(file="imageedit_4_8477195169.gif")
photolbl = Label(about_window, image=photo4, borderwidth=0)
photolbl.image = photo4
photolbl.pack()
lbl3 = Label(about_window, text="Cookie Clicker", bg="snow2", fg="black", font=("Lucida Grande bold", 14))
lbl3.pack()
lbl4 = Label(about_window, text="Version 13.0.4 (24502.5.6)", bg="snow2", fg="black", font=("Lucida Grande", 9))
lbl4.pack()
copyright_symb = u'\N{COPYRIGHT SIGN}'.encode('utf-8')
lbl5 = Label(about_window, text="Copyright {0} 2003-2018 Hatna Inc.\nAll rights reserved.".format(copyright_symb), bg="snow2", fg="black", font=("Lucida Grande", 10))
lbl5.pack()
def shop_btn():
def autoclick():
def tensecs():
while True:
global clicks
clicks = clicks + 1
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
shop_window.after(1000, tensecs)
def double():
global clicks
if clicks >= 20:
clicks = clicks * 2
clicks = clicks - 20
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
shop_window.destroy()
global lbl3
lbl3.configure(text="", fg="dodger blue")
else:
shop_window.destroy()
lbl3.configure(text="You Need More Cookies!", fg="snow2")
shop_window = Toplevel(window1)
shop_window.overrideredirect(1)
shop_window.geometry("254x310+5+50")
frame = Frame(shop_window, width=254, height=310)
frame.pack()
canvas = Canvas(frame, width=254, height=310, bg="dodger blue", bd=0, highlightthickness=0, relief="ridge", scrollregion=(0, 0, 500, 500))
vbar = Scrollbar(frame, orient=VERTICAL)
vbar.pack(side=RIGHT, fill=Y)
vbar.config(command=canvas.yview)
canvas.config(yscrollcommand=vbar.set)
canvas.pack()
canvas.create_rectangle(0, 0, 254, 40, outline="snow2", fill="snow2")
lbl3 = canvas.create_text(135, 20, text="{0} Cookies".format(clicks), fill="dodger blue", font=("kavoon", 15))
global photo5
photo5 = PhotoImage(file="imageedit_1_6195264074.gif")
photolbl = canvas.create_image(20, 20, image=photo5)
x2 = canvas.create_text(35, 120, text="X2", fill="gray", font=("arial bold", 40))
lbl4 = canvas.create_text(115, 110, text="Double Your Score", fill="black", font=("arial bold", 12))
lbl5 = canvas.create_text(94, 129, text="20 Cookies", fill="black", font=("arial", 12))
buybtn1 = Button(canvas, text="Buy", highlightbackground="dodger blue", command=double)
buybtn1_window = canvas.create_window(210, 119.5, window=buybtn1)
global photo6
photo6 = PhotoImage(file="imageedit_24_7373388957.gif")
photolbl2 = canvas.create_image(32.5, 70, image=photo6)
lbl6 = canvas.create_text(124, 61, text="10 Second Auto-Click", fill="black", font=("arial bold", 12))
lbl5 = canvas.create_text(94, 80, text="15 Cookies", fill="black", font=("arial", 12))
buybtn2 = Button(canvas, text="Buy", highlightbackground="dodger blue", command=autoclick)
buybtn2_window = canvas.create_window(210, 70, window=buybtn2)
w = Canvas(window1, width=254, height=80, highlightbackground="snow2")
w.pack()
w.create_rectangle(10, 10, 80, 80, outline="snow2", fill="snow2", width=100000)
cookie = Button(window1, highlightbackground="dodger blue", borderwidth=0, cursor="hand2")
cookie.bind('<Button-1>', cookie_clicks)
window1.bind('<Return>', cookie_clicks)
photo = PhotoImage(file="imageedit_3_3213999137.gif")
cookie.config(image=photo, width="250", height="250")
cookie.place(x=0, y=90)
w2 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w2.place(x=0, y=86)
w3 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w3.place(x=249, y=86)
w4 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w4.place(x=0, y=88)
w5 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w5.place(x=0, y=338)
lbl1 = Label(window1, bg="snow2", fg="dodger blue", text="{0} Cookies!".format(clicks), font=("kavoon", 20))
lbl1.place(x=75, y=40)
lbl2 = Label(window1, bg="snow2", fg="dodger blue", text="Cookie Clicker", font=("kavoon", 30))
lbl2.place(x=20, y=0)
pb = ttk.Progressbar(window1, orient='horizontal', mode='determinate')
pb.place(x=76, y=68)
shop = Button(window1, highlightbackground="dodger blue", borderwidth=0, command=shop_btn)
photo2 = PhotoImage(file="imageedit_28_9392607524.gif")
shop.config(image=photo2, width="44", height="40")
shop.place(x=5, y=345)
w6 = Canvas(window1, width=38, height=0.1, highlightbackground="dodger blue")
w6.place(x=7, y=345)
w7 = Canvas(window1, width=38, height=0.1, highlightbackground="dodger blue")
w7.place(x=7, y=381)
w8 = Canvas(window1, width=0.1, height=25, highlightbackground="dodger blue")
w8.place(x=6, y=350)
w9 = Canvas(window1, width=0.1, height=25, highlightbackground="dodger blue")
w9.place(x=45, y=350)
info = Button(window1, highlightbackground="dodger blue", borderwidth=0, command=about_btn)
photo3 = PhotoImage(file="imageedit_48_3021448243.gif")
info.config(image=photo3, width="44", height="40")
info.place(x=49, y=345)
w10 = Canvas(window1, width=38, height=0.1, highlightbackground="dodger blue")
w10.place(x=51, y=345)
w11 = Canvas(window1, width=38, height=0.1, highlightbackground="dodger blue")
w11.place(x=51, y=381)
w12 = Canvas(window1, width=0.1, height=25, highlightbackground="dodger blue")
w12.place(x=50, y=350)
w13 = Canvas(window1, width=0.1, height=25, highlightbackground="dodger blue")
w13.place(x=90, y=350)
lbl3 = FlashableLabel(window1, bg="dodger blue", fg="dodger blue", text="", font=("kavoon", 12))
lbl3.place(x=100, y=353)
lbl3.flash(0)
window1.mainloop()
Any help would be appreciated! and please excuse my GUI's bad formatting, I've not quite began to experiment with .grid.

You need to use after() instead of a while loop, not in addition to. Try this:
def autoclick():
global clicks
clicks = clicks + 1
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
shop_window.after(1000, autoclick) # repeat this function every second

Related

Tkinter Entry widget sees empty string, cannot convert to float because of it

I'm trying to make a Density/Volume/Mass calculator. When I enter the values in the Entry widgets and click the button, I get a ValueError: could not convert string to float: '' message. What am I missing? Why doesnt it see the entered values? Oddly, I first made only the density calculator part, and it worked perfectly. Now it doesn't.
import tkinter as tk
from tkinter import ttk
def density_calculator():
def density():
vol = float(vol_value.get())
mas = float(mass_value.get())
dens = mas / vol
calculated_density = ttk.Label(root, text=f"{dens}", font=("Helvetica", 20))
calculated_density.place(x=280, y=290)
density_w = tk.Tk()
density_w.title("Density Calculator")
density_w.geometry("600x400")
density_w.resizable(False, False)
vol_value = tk.StringVar()
mass_value = tk.StringVar()
volume = ttk.Label(density_w, text="Volume (cm^3)", relief="ridge", font=("Helvetica", 20))
mass = ttk.Label(density_w, text="Mass (g)", relief="ridge", font=("Helvetica", 20))
density_label = ttk.Label(density_w, text="Density (g/cm3)", relief="ridge", font=("Helvetica", 20))
volume_entry = ttk.Entry(density_w, textvariable=vol_value)
mass_entry = ttk.Entry(density_w, textvariable=mass_value)
volume.place(x=65, y=50)
mass.place(x=405, y=50)
density_label.place(x=200, y=250)
volume_entry.place(x=100, y=100)
mass_entry.place(x=400, y=100)
done_button = ttk.Button(density_w, text="Calculate", command=density)
done_button.place(x=480, y=350)
density_w.mainloop()
def volume_calculator():
def volume():
vol = float(dens_value.get())
mas = float(mass_value.get())
dens = mas / vol
calculated_density = ttk.Label(root, text=f"{dens}", font=("Helvetica", 20))
calculated_density.place(x=280, y=290)
volume_w = tk.Tk()
volume_w.title("Volume Calculator")
volume_w.geometry("600x400")
volume_w.resizable(False, False)
dens_value = tk.StringVar()
mass_value = tk.StringVar()
density = ttk.Label(volume_w, text="Density (g/cm^3)", relief="ridge", font=("Helvetica", 20))
mass = ttk.Label(volume_w, text="Mass (g)", relief="ridge", font=("Helvetica", 20))
volume_label = ttk.Label(volume_w, text="Volume (cm3)", relief="ridge", font=("Helvetica", 20))
density_entry = ttk.Entry(volume_w, textvariable=dens_value)
mass_entry = ttk.Entry(volume_w, textvariable=mass_value)
density.place(x=65, y=50)
mass.place(x=405, y=50)
volume_label.place(x=200, y=250)
density_entry.place(x=100, y=100)
mass_entry.place(x=400, y=100)
done_button = ttk.Button(volume_w, text="Calculate", command=volume)
done_button.place(x=480, y=350)
volume_w.mainloop()
root = tk.Tk()
root.title("Density, Volume, Mass Calculator")
root.geometry("200x100")
root.resizable(False, False)
density_choice = ttk.Radiobutton(root, text="Calculate Density", command=density_calculator)
volume_choice = ttk.Radiobutton(root, text="Calculate Volume", command=volume_calculator)
mass_choice = ttk.Radiobutton(root, text="Calculate Density")
density_choice.place(x=0, y=0)
volume_choice.place(x=0, y=20)
root.mainloop()
After changing the following two things your code is now working fine
Replace StringVar variable with entry variable when getting value
Use actual window name in the Label creation for showing result
Final code is following
import tkinter as tk
from tkinter import ttk
def density_calculator():
def density():
vol = float(volume_entry.get())
mas = float(mass_entry.get())
dens = round(mas / vol, 2)
calculated_density = ttk.Label(density_w, text=f"{dens}", font=("Helvetica", 20))
calculated_density.place(x=280, y=290)
density_w = tk.Tk()
density_w.title("Density Calculator")
density_w.geometry("600x400")
density_w.resizable(False, False)
vol_value = tk.StringVar()
mass_value = tk.StringVar()
volume = ttk.Label(density_w, text="Volume (cm^3)", relief="ridge", font=("Helvetica", 20))
mass = ttk.Label(density_w, text="Mass (g)", relief="ridge", font=("Helvetica", 20))
density_label = ttk.Label(density_w, text="Density (g/cm3)", relief="ridge", font=("Helvetica", 20))
volume_entry = ttk.Entry(density_w, textvariable=vol_value)
mass_entry = ttk.Entry(density_w, textvariable=mass_value)
volume.place(x=65, y=50)
mass.place(x=405, y=50)
density_label.place(x=200, y=250)
volume_entry.place(x=100, y=100)
mass_entry.place(x=400, y=100)
done_button = ttk.Button(density_w, text="Calculate", command=density)
done_button.place(x=480, y=350)
density_w.mainloop()
def volume_calculator():
def volume():
vol = float(density_entry.get())
mas = float(mass_entry.get())
dens = round(mas / vol, 2)
calculated_density = ttk.Label(volume_w, text=f"{dens}", font=("Helvetica", 20))
calculated_density.place(x=280, y=290)
volume_w = tk.Tk()
volume_w.title("Volume Calculator")
volume_w.geometry("600x400")
volume_w.resizable(False, False)
dens_value = tk.StringVar()
mass_value = tk.StringVar()
density = ttk.Label(volume_w, text="Density (g/cm^3)", relief="ridge", font=("Helvetica", 20))
mass = ttk.Label(volume_w, text="Mass (g)", relief="ridge", font=("Helvetica", 20))
volume_label = ttk.Label(volume_w, text="Volume (cm3)", relief="ridge", font=("Helvetica", 20))
density_entry = ttk.Entry(volume_w, textvariable=dens_value)
mass_entry = ttk.Entry(volume_w, textvariable=mass_value)
density.place(x=65, y=50)
mass.place(x=405, y=50)
volume_label.place(x=200, y=250)
density_entry.place(x=100, y=100)
mass_entry.place(x=400, y=100)
done_button = ttk.Button(volume_w, text="Calculate", command=volume)
done_button.place(x=480, y=350)
volume_w.mainloop()
root = tk.Tk()
root.title("Density, Volume, Mass Calculator")
root.geometry("200x100")
root.resizable(False, False)
density_choice = ttk.Radiobutton(root, text="Calculate Density", command=density_calculator)
volume_choice = ttk.Radiobutton(root, text="Calculate Volume", command=volume_calculator)
mass_choice = ttk.Radiobutton(root, text="Calculate Density")
density_choice.place(x=0, y=0)
volume_choice.place(x=0, y=20)
root.mainloop()
Output is Following

How to change a frame in tkinter, after keeping it alive for a few seconds

I'm working on a color detector project with raspberry pi.
the flow is:
a welcome screen is displayed when the program starts, as soon as the color sensor detects a color it takes us to the next screen to enter a number.
As the color sensor used is TCS3200 and it continuously gives us value, many a time it happens to detect the color, even when there is no color and it takes to next screen.
What I want to do is, whenever a color is detected and it goes to the next screen, that screen should be active for 15 seconds, and should go back to the welcome screen again.
I tried using time.sleep, but whenever I issue that, the frame raise never happens, and after 10 seconds it shows me the welcome screen.
I'm putting my code here
import RPi.GPIO as GPIO
import time
from tkinter import *
import tkinter.font as tkFont
from PIL import Image, ImageTk
def raise_frame(frame):
frame.tkraise()
#Declare Global Variables
root = None
dfont = None
welcome = None
msg = None
value = None
number = ""
#GPIO pins
aux_vcc = 16
s2 = 5
s3 = 6
signal = 26
NUM_CYCLES = 10
#Fulscreen or windowed
fullscreen = False
def number_e():
global number
num = number.get()
number.set(num)
print(num)
num=""
number.set(num)
raise_frame(PageTwo)
def num_get(num):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(num))
def delt():
temp = e.get()[:-1]
e.delete(0, END)
e.insert(0, temp)
def clr():
e.delete(0, END)
def cancel():
raise_frame(welcome)
#toggle fullscreen
def toggle_fullscreen(event=None):
global root
global fullscreen
fullscreen = not fullscreen
root.attributes('-fullscreen', fullscreen)
resize()
#go into windowed mode
def end_fullscreen(event=None):
global root
global fullscreen
fullscreen = False
root.attributes('-fullscreen', False)
resize()
#resize font based on screen size
def resize(event=None):
global dfont
global welcome
new_size = -max(12, int((welcome.winfo_height() / 10)))
dfont.configure(size=new_size)
def setup():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(signal, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(aux_vcc, GPIO.OUT)
GPIO.output(aux_vcc, GPIO.HIGH)
GPIO.setup(s2, GPIO.OUT)
GPIO.setup(s3, GPIO.OUT)
print("\n")
def endprogram():
GPIO.cleanup()
def loop():
temp = 1
global root
global value
global number
global num
GPIO.output(s2,GPIO.LOW)
GPIO.output(s3,GPIO.LOW)
time.sleep(0.3)
start = time.time()
for impulse_count in range(NUM_CYCLES):
GPIO.wait_for_edge(signal, GPIO.FALLING)
duration = time.time() - start #seconds to run for loop
red = NUM_CYCLES / duration #in Hz
print("red value - ",red)
GPIO.output(s2,GPIO.LOW)
GPIO.output(s3,GPIO.HIGH)
time.sleep(0.3)
start = time.time()
for impulse_count in range(NUM_CYCLES):
GPIO.wait_for_edge(signal, GPIO.FALLING)
duration = time.time() - start
blue = NUM_CYCLES / duration
print("blue value - ",blue)
GPIO.output(s2,GPIO.HIGH)
GPIO.output(s3,GPIO.HIGH)
time.sleep(0.3)
start = time.time()
for impulse_count in range(NUM_CYCLES):
GPIO.wait_for_edge(signal, GPIO.FALLING)
duration = time.time() - start
green = NUM_CYCLES / duration
print("green value - ",green)
time.sleep(0.5)
if ((red >= 3600 and red <= 4299) and (blue >= 3900 and blue <= 5850) and (green >= 5150 and green <= 6300)):
raise_frame(PageOne)
elif ((red >= 3600 and red <= 4999) and (blue >= 4199 and blue <= 4800) and (green >= 4500 and green <= 5950)):
raise_frame(PageOne)
elif ((red >= 4400 and red <= 4699) and (blue >= 4150 and blue <= 5000) and (green >= 4100 and green <= 4950)):
raise_frame(PageOne)
elif ((red >= 3600 and red <= 4399) and (blue >= 5000 and blue <= 5600) and (green >= 3900 and green <= 4499)):
raise_frame(PageOne)
else:
pass
root.after(500, loop)
#create the window
root = Tk()
root.title("Screen")
root.geometry('800x480')
welcome = Frame(root)
PageOne = Frame(root)
PageTwo = Frame(root)
for frame in (welcome, PageOne, PageTwo):
frame.grid(row=6, column=3, sticky='news')
value = DoubleVar()
msg = StringVar()
number = StringVar()
dfont = tkFont.Font(size=-6)
myfont = tkFont.Font(size=20)
mfont = tkFont.Font(size=12)
wel = Label(welcome, text="Welcome.", font=myfont)
wel.grid(row=1, column=1, padx=0, pady=0)
wel.place(x=50, y=320)
load = Image.open("banner.png")
load = load.resize((800,250), Image.BICUBIC)
render = ImageTk.PhotoImage(load)
img = Label(welcome, image=render)
img.image = render
img.place(x=0, y=0)
img.grid(row=0, column=0)
Label(PageOne, text="Enter your Mobile Number to get reward: ", font=myfont).grid(columnspan=3, row=0, column=0, padx=100, pady=50)
e = Entry(PageOne, textvariable=number, width=30, font=myfont)
e.grid(columnspan=3, row=1, column=0, padx=150, pady=15)
Button(PageOne, text='1', command=lambda:num_get(1), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=2, column=0)
Button(PageOne, text='2', command=lambda:num_get(2), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=2, column=1)
Button(PageOne, text='3', command=lambda:num_get(3), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=2, column=2)
Button(PageOne, text='4', command=lambda:num_get(4), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=3, column=0)
Button(PageOne, text='5', command=lambda:num_get(5), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=3, column=1)
Button(PageOne, text='6', command=lambda:num_get(6), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=3, column=2)
Button(PageOne, text='7', command=lambda:num_get(7), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=4, column=0)
Button(PageOne, text='8', command=lambda:num_get(8), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=4, column=1)
Button(PageOne, text='9', command=lambda:num_get(9), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=4, column=2)
Button(PageOne, text='0', command=lambda:num_get(0), borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=5, column=1)
Button(PageOne, text='Delete', command=delt, borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=5, column=2)
Button(PageOne, text='Clear', command=clr, borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=5, column=0)
Button(PageOne, text='Enter', bg='#0052cc', fg='#ffffff', command=number_e, borderwidth=5, relief=RAISED, height=1, width=20, font=myfont).grid(row=6, column=0, columnspan=2)
Button(PageOne, text='Cancel', command=cancel, borderwidth=5, relief=RAISED, height=1, width=10, font=myfont).grid(row=6, column=2)
Label(PageTwo, text=" ", font=myfont).grid(row=0, column=1, padx=5, pady=5)
Label(PageTwo, text="Thank You", font=myfont).grid(row=1, column=1, padx=150, pady=200)
root.bind('<F11>', toggle_fullscreen)
root.bind('<Escape>', end_fullscreen)
root.bind('<Configure>', resize)
setup()
root.after(1000, loop)
raise_frame(welcome)
toggle_fullscreen()
root.mainloop()

Change ttk Progress Bar Background In Tkinter

I've been working on a cookie clicker program which includes a progress Bar widget. The progress bar is working perfectly, however when I run my program, the progress bar is surrounded by an ugly grey border.I have tried using highlightbackground but that does nothing. I am working on Mac OSX.
Here's an image of the progress bar when the program is run: https://i.stack.imgur.com/Y7Tue.png
Here is my code:
from Tkinter import *
from Tkinter import Canvas
import ttk
window1 = Tk()
window1.title("Cookie Clicker")
window1.config(background="dodger blue")
window1.geometry("254x370")
clicks = 0
def cookie_clicks():
global clicks
clicks = clicks + 1
pb.step(1)
print("{0}".format(clicks))
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
cookie = Button(window1, highlightbackground="dodger blue", borderwidth=0, cursor="hand2", command=cookie_clicks)
photo = PhotoImage(file="imageedit_3_3213999137.gif")
cookie.config(image=photo, width="250", height="250")
cookie.place(x=0, y=90)
w = Canvas(window1, width=254, height=80, highlightbackground="gray")
w.pack()
w.create_rectangle(10, 10, 80, 80, outline="gray", fill="gray", width=100000)
w2 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w2.place(x=0, y=85)
w3 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w3.place(x=249, y=85)
w4 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w4.place(x=0, y=88)
w5 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w5.place(x=0, y=338)
lbl1 = Label(window1, bg="gray", fg="dodger blue", text="{0} Cookies!".format(clicks), font=("kavoon", 20))
lbl1.place(x=75, y=40)
lbl2 = Label(window1, bg="gray", fg="dodger blue", text="Cookie Clicker", font=("kavoon", 30))
lbl2.place(x=20, y=0)
pb = ttk.Progressbar(window1, orient='horizontal', mode='determinate')
pb.place(x=76, y=68)
window1.mainloop()
Any help would be appreciated!

Tkinter Link Button With Progress Bar

I'm creating a cookie clicker app using Tkinter. I want to have a progress bar in my program that fills up every time the cookie is clicked 100 times. I have created the progress bar using import ttk, however I don't know how to make the progress bar update whenever the button is pressed.
Here is my code so far:
from Tkinter import *
from Tkinter import Canvas
import ttk
window1 = Tk()
window1.title("Cookie Clicker")
window1.config(background="dodger blue")
window1.geometry("254x370")
clicks = 0
def cookie_clicks():
global clicks
clicks = clicks + 1
print("{0}".format(clicks))
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
cookie = Button(window1, highlightbackground="dodger blue", borderwidth=0, cursor="hand2", command=cookie_clicks)
photo = PhotoImage(file="imageedit_3_3213999137.gif")
cookie.config(image=photo, width="250", height="250")
cookie.place(x=0, y=90)
w = Canvas(window1, width=254, height=75, highlightbackground="gray")
w.pack()
w.create_rectangle(10, 10, 80, 80, outline="gray", fill="gray", width=100000)
w2 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w2.place(x=0, y=85)
w3 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w3.place(x=249, y=85)
w4 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w4.place(x=0, y=88)
w5 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w5.place(x=0, y=338)
lbl1 = Label(window1, bg="gray", fg="dodger blue", text="{0} Cookies!".format(clicks), font=("kavoon", 20))
lbl1.place(x=75, y=45)
lbl2 = Label(window1, bg="gray", fg="dodger blue", text="Cookie Clicker", font=("kavoon", 30))
lbl2.place(x=20, y=0)
pb = ttk.Progressbar(window1, orient='horizontal', mode='determinate')
pb.pack()
window1.mainloop()
Any help would be appreciated!
Without changing your code much, you can do:
def cookie_clicks():
global clicks, pb
clicks = clicks + 1
pb.step(1)
print("{0}".format(clicks))
if clicks == 1:
lbl1.configure(text="{0} Cookie!".format(clicks))
else:
lbl1.configure(text="{0} Cookies!".format(clicks))
It is not great to use global variables. You should look into encapsulating your app in a class.

Why is my code printing ".!canvas.!entry"?

I don't understand what is going on. I have defined 2 functions. 1 function displays text, entry boxes, and a submit button. I have it so that when the submit button is pressed, it prints the information the user put inside of the entry boxes. I've shortened my code for easier readability.
from tkinter import *
from PIL import Image, ImageTk
canvas_width = 360
canvas_height = 525
file = r"C:\Users\kraak\Desktop\PyCharm Community Edition 2017.1.2\borderedpaper.GIF"
master = Tk()
canvas = Canvas(master, width=canvas_width, height=canvas_height)
old_img = PhotoImage(file=file)
new_img = old_img.subsample(3, 3)
canvas.create_image(-11, -10, anchor=NW, image=new_img)
canvas.create_window(0, 0, height=1, width=1, anchor=NW)
canvas.create_text(0, 0, text="Test")
e1 = Entry(canvas)
def callback():
print(e1)
def answer():
e1 = Entry(canvas)
canvas.create_window(250, 100, window=e1, height=15, width=100)
label = Label(text="Enter a word.")
label.place(x=40, y=90)
e2 = Entry(canvas)
canvas.create_window(250, 125, window=e2, height=15, width=100)
label = Label(text="Enter a word.")
label.place(x=40, y=115)
button = Button(text="Submit.", command=callback)
button.place(x=150, y=460)
answer()
canvas.pack()
mainloop()

Categories