Tkinter wait function is not working - python

I am trying to make an animation using Tkinter Text Widget. I want it to write each frame on the Text widget every 1 second. Here is my current code:
from tkinter import *
frames = ["-o","--o","---o"]
speed = 1000
def clear():
text.delete(0.0, END)
def movie(event):
text.delete(0.0, END)
for frame in range(len(frames)):
text.insert(END, frames[frame])
root.after(speed, clear)
root = Tk()
root.title("Animation")
root.minsize(400,400)
root.maxsize(width=root.winfo_screenwidth()-20, height=root.winfo_screenheight()-20)
text = Text(root, highlightcolor="black", highlightbackground="white",width=400, insertbackground="white", height=400, foreground="white", background="black", font="Courier")
text.pack()
root.bind("<Return>", movie)
But, the output of this code is
-o--o---o
instead of:
-o[wait a second][clear]--o[wait a second][clear]---o[wait a second][clear]
How can I fix this?

I found my problem! The .after() function almost works like the return function. In that, when called the current function is stopped. This is my fixed code:
from tkinter import *
frame = 0
frames = ["-o","--o","---o"]
speed = 1000
def clear():
text.delete(0.0, END)
def movie(event=""):
global frame
if frame < len(frames):
text.delete(0.0, END)
text.insert(END,frames[frame])
frame += 1
root.after(speed, movie)
def movie1(event):
global frame
frame = 0
movie("<Return>")
root = Tk()
root.title("Animation")
root.minsize(400,400)
root.maxsize(width=root.winfo_screenwidth()-20, height=root.winfo_screenheight()-20)
text = Text(root, highlightcolor="black", highlightbackground="white",width=400, insertbackground="white", height=400, foreground="white", background="black", font="Courier")
text.pack()
root.bind("<Return>", movie)

Related

How can I either ignore blank pages in a pdf using python or add blank pages to a location without changing the total amnt of pages until doc saved?

So I'm using the tkinter and pymupdf libraries to add blank pages to a desired location. This is done by pressing a button which inserts the blank page below the page on the button. My issue is that once it inserts the blank page, the original page order now changes.
When you press a button corresponding to a page number, it inserts the blank page, but if you try with a second blank page, it inserts it at the wrong place because it messes up the button's assigned page number. Please help I'm losing my hair.
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfilename
import fitz
btnClick = 0
def launchInsert():
global root
global buttonframe
root = tk.Tk()
root.title("Bla bla bla")
root.geometry("800x600")
#Displays "text" name as title of program
label = tk.Label(root, text ="Insert Blank Page", font=('Arial',18))
label.pack(padx=20, pady=20)
#File Explorer Button
buttonframe = tk.Frame(root, padx=100, pady=25)
btn1 = tk.Button(buttonframe,text="Browse...", font=('Arial',18), command=browse_file)
btn1.grid(row=1, column=6, padx=225, sticky=tk.W+tk.E)
buttonframe.pack(side="bottom")
def save_file():
f = asksaveasfilename(initialfile = 'untitled.pdf',
defaultextension=".pdf",filetype=[("All Files","*.*"),("PDF Files","*.pdf")])
pdf2.save(f)
# with open(file, "wb") as pdfCombined:
# newPdf.write(pdfCombined)
def blank(i):
#program is recognizing blank page as document original page then counting it as pagenumber
#try to just ignore blank pages
pdf2.new_page(pno=i, width=595, height=842)
global btnClick
btnClick = btnClick + 1
if btnClick == 1:
pdf2.new_page(pno=i, width=595, height=842)
elif btnClick > 1:
print("This is button click: ", btnClick)
i = i + 1
pdf2.new_page(pno=i, width=595, height=842)
for slices in range(len(pdf2)):
print("This is new page - ", slices)
print("This is pageCount after addition", slices)
print("The page was added successfully")
print("This is ", i)
def browse_file():
global filename
filename = filedialog.askopenfilename(title="Select a File", filetype=(("PDF Files","*.pdf"),("All Files","*.*")))
global pdf2, pageCount, i
pdf2 = fitz.open(filename)
# Create A Main Frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
# Create A Canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
# Add A Scrollbar To The Canvas
my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
# Configure The Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))
# Create ANOTHER Frame INSIDE the Canvas
second_frame = Frame(my_canvas)
# Add that New frame To a Window In The Canvas
my_canvas.create_window((0,0), window=second_frame, anchor="nw")
btn2 = tk.Button(buttonframe,text="Save", font=('Arial',18), command=save_file)
btn2.grid(row=1, column=7, pady=20, sticky=tk.W+tk.E)
buttonframe.pack(side="bottom")
for i in range(len(pdf2)):
insClick = tk.Button(second_frame, text=f'Insert\nbelow {i}', padx= 50, command= lambda i=i: blank(i)).grid(row=i, column=5, pady=25, padx=50)
numShow = Label(second_frame, text=f"Page number {i}",padx=200).grid(row=i, column=1)
launchInsert()
mainloop()

How do I create a +1 button in tkinter

**I am writing a baseball counting program. I have a label for walks and strikeouts. To the side of those labels I have buttons with the text "+1". I want the buttons to be able to change and print the number of walks and strikeouts every time I click the +1 buttons. I just need some ideas to help get started. Here is my code for clarification: **
import tkinter as tk
from tkinter.constants import COMMAND, X
global walk_counter
walk_counter = 0
global strikeout_counter
strikeout_counter = 0
def main(): # This is the main function
root = tk.Tk()
frame = tk.Frame(root)
frame.master.title("Random Title")
frame.pack(padx=4, pady=3, fill=tk.BOTH, expand=1)
populate_boxes(frame)
root.mainloop()
def populate_boxes(frame):
walks_label = tk.Label(frame, text="BB:")
walks_entry = tk.Label(frame, width=4)
walks_button = tk.Button(frame,text="+1")
strikeouts_label = tk.Label(frame,text="Strikeouts:")
strikeouts_entry = tk.Label(frame,width=4)
strikeouts_button = tk.Button(frame,text="+1")
walks_label.place(x=200,y=500)
walks_entry.place(x=250,y=500)
walks_button.place(x=300,y=500)
strikeouts_label.place(x=400,y=500)
strikeouts_entry.place(x=450,y=500)
strikeouts_button.place(x=500,y=500)
def add_more_walks():
global walk_counter
walk_counter += 1
walks_entry.config(text = walk_counter)
add_more_walks()
main()

Tkinter raises an blank frame error even when I packed first frame

The code below is simple i am just creating two frames and trying to display progressbar with image in first then after 6 seconds switching two frame 2 but the first frame is completely white for some reason. Hope someone can help :)
from PIL import ImageTk,Image
from tkinter import ttk
import time
frames=['frame1','frame2']
#canvas
root=Tk()
root.title('Anigame Tools V1.0')
root.iconbitmap('anigametoolsicon.ico')
#Frame Functions
frame1= Frame(root)
frame2= Frame(root)
frame1.pack()
frames=[frame1,frame2]
# progress bar
p = ttk.Progressbar(frame1, orient=HORIZONTAL, length=200, mode="determinate", takefocus=True, maximum=100)
p['value'] = 0
p.grid(row=1, column=0)
def start():
if p['value'] != 80:
p['value'] += 20
root.after(1000, start)
frame1.after(1000, start)
def show_frame(framename):
for i in frames:
i.pack_forget()
framename.pack()
# intro
intimg=Image.open("anigametoolsicon.png")
introimg = ImageTk.PhotoImage(intimg)
intro = Label(frame1,image=introimg)
intro.grid(row=0, column=0)
# frame2
anigametoolsad = Label(frame2, text='Anigame Tools Ver1.0')
anigametoolsad.grid(column=0, row=0, columnspan=3)
root.after(6000, show_frame(frame2))
root.mainloop()

Tkinter pack after destroying

Just a simple example of a problem I experienced:
from tkinter import *
root = Tk()
frame = Frame(root)
label = Label(frame, text = "Hey")
label.pack()
def packframe():
frame.pack()
def destroyframe():
frame.destroy()
pack_button = Button(root, text = "pack", command = packframe)
pack_button.pack()
des_button = Button(root, text = "destroy", command = destroyframe)
des_button.pack()
Once I press the destroy button, I cannot pack it back again on the screen with the pack_button. Im not sure why is it so, but I would appreciate both explanaition and a solution

How do I use a tkinter entry as a parameter for a function

I would like a text box to ask for input in a tkinter window, then use that input as a parameter to call a function that draws a Sierpinski triangle. My buttons work but my input box does not. I keep trying to fix my code but it is not working, any help would be appreciated.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root.title('Fractals') #titles the button box
top_frame = tk.Frame()
mid_frame = tk.Frame()
prompt_label = tk.Label(top_frame, \
text='Enter a number of iterations (more is better):')
iterations = tk.Entry(root,bd=1)
itr=iterations.get()
itr=int(itr)
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
sTriangle = tk.Button(frame,
text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),
(0,500),itr))
sTriangle.pack(side=tk.LEFT)
fsquare = tk.Button(frame,
text="Square",
command=fractalsquare(fred,(-500,-500),(500,-500),
(500,500),(-500,500),itr))
fsquare.pack(side=tk.LEFT)
root.mainloop()
There are several issues:
1) Choose one way to import tkinter or confusion will result
2) You should provide a master for your Frames and then pack them. Pay attention on where the frames appear and what they contain.
3) It's usual to assign a textvariable to the Entry which will contain what you enter into it. The textvariable should be a tk.StringVar.
4) If a Button has a callback function, it must be defined before you create the button.
5) The variable fred is not defined.
Example of how you can write it:
import tkinter as tk
root = tk.Tk()
root.title('Fractals') #titles the button box
# Create the Label at the top
top_frame = tk.Frame(root) # Top Frame for
top_frame.pack()
prompt_label = tk.Label(top_frame,
text='Enter a number of iterations (more is better):')
prompt_label.pack()
# Create the Entry in the middle
mid_frame = tk.Frame(root)
mid_frame.pack()
itr_string = tk.StringVar()
iterations = tk.Entry(mid_frame,textvariable=itr_string)
iterations.pack()
fred=None # Was not defined...
# Create Buttons at the bottom
bot_frame = tk.Frame(root)
bot_frame.pack()
button = tk.Button(bot_frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)
def sierpinski(*args): # sTriangle button callback function
itr = int(itr_string.get()) # How to get text from Entry
# if Entry does not contain an integer this will throw an exception
sTriangle = tk.Button(bot_frame, text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),(0,500),itr_string))
sTriangle.pack(side=tk.LEFT)
def fractalsquare(*args): pass # fsquare button callback function
fsquare = tk.Button(bot_frame, text="Square", command=fractalsquare(fred,
(-500,-500),(500,-500),(500,500),(-500,500),itr_string))
fsquare.pack(side=tk.LEFT)
root.mainloop()
You should seriously study a basic tkinter tutorial. Try this one: An Introduction To Tkinter

Categories

Resources