Home > Back-end >  Animate a tkinter frame
Animate a tkinter frame

Time:11-04

I want to create a tkinter animation in which a frame on all its contents move from right to left. After clicking the button, the frame and its contents should move from left to right. I was able to achieve the former but when I click the button, the frame and its contents disappear.



import tkinter as tk
from tkinter import *

def contract(i):
    if i<=425:
        b.place(x=i)
        b.after(5, lambda: contract(i))
        i = i 1

def expand(i):
    if i>=100:
        b.place(x=i)
        b.after(5, lambda: expand(i)) 
        i = i-1
        
root = tk.Tk()
root.geometry('425x670')
b =Frame(root,bg='red',height=670,width=400)
b.pack()
b.grid_propagate(0)
button=Button(b,text="withdraw",command=lambda: contract(425))
button.grid(row=0,column=0)




expand(425) 
root.mainloop()
---------------------------------
I'd like a solution that would fix this problem.

I'm just a beginner at tkinter and I would appreciate your help!

CodePudding user response:

I had tested your code, when the windows is expanded, you can see that after button is clicked, the section teleported back to the original position. In another word, the section did not disappear, it instead reach the destination instantly. This is cause by you using i as parameter in contract(), since x=i, passing 425 into i will make x=425 instantly. My solution to this is to use 2 parameter, an original position and a target, the original will increment until it hits the target, and x will be set to the original value. Here is my edited code:

import tkinter as tk
from tkinter import *

def contract(original,target):
    if original<=target:
        b.place(x=original)
        b.after(5, lambda: contract(original,target))
        original  = 1

def expand(original, target):
    if original>=target:
        b.place(x=original)
        b.after(5, lambda: expand(original, target)) 
        original -= 1
        
root = tk.Tk()
root.geometry('425x670')
b =Frame(root,bg='red',height=670,width=400)
b.pack()
b.grid_propagate(0)
button=Button(b,text="withdraw",command=lambda: contract(100,425))
button.grid(row=0,column=0)




expand(425,100) 
root.mainloop()

Hopefully that can help you!

*edit: I notice the problem that after it contract and you click the button again, it will repeat the animation from 100 -> 425, you may want to implement a logic to control which function the button is triggering.

  • Related