Home > Back-end >  Tkinter problem making 30 degree angle multiple times
Tkinter problem making 30 degree angle multiple times

Time:11-16

I have a problem https://prnt.sc/1znuffv with tkinter, I need it to reach from 0 to 180 degrees with making "checkpoint" every 30 degrees, I got help on this site to successfully done to reach 0-180 and back but cannot make it 30 by 30.

import tkinter as tk
root = tk.Tk()
root.geometry("800x800")
root.resizable(0, 0)

s = 0
def menjajKanvas(arc):
global s
if s < 180:
    s =1
    c.itemconfig(arc,extent=s,fill="red")
    root.after(10,menjajKanvas,arc)
else:
    shrink_arc(arc)
def shrink_arc(arc):
global s
if s >= 0:
    s-=1
    c.itemconfig(arc,extent=s,fill="red")
    root.after(10,shrink_arc,arc)
else:
    root.after(10,menjajKanvas,arc)

c = tk.Canvas(root, height=250, width=300, bg="blue")
c.pack()
arc = c.create_arc(10,50,240,210,
               extent=150,
               outline="red",
               fill='red',
               tags=("arc",))
menjajKanvas(arc)
root.mainloop()

CodePudding user response:

You could use a variable delay in your function calls issued via tk.after:

something like this:

import tkinter as tk


def menjajKanvas(arc):
    global s
    if s < 180:
        s  = 1
        c.itemconfig(arc, extent=s,f ill="red")
        delay = 10 if s % 30 else 1000
        root.after(delay, menjajKanvas, arc)
    else:
        root.after(1000, shrink_arc, arc)


def shrink_arc(arc):
    global s
    if s >= 0:
        s -= 1
        c.itemconfig(arc, extent=s, fill="red")
        delay = 10 if s % 30 else 1000
        root.after(delay, shrink_arc, arc)
    else:
        root.after(1000, menjajKanvas, arc)


if __name__ == '__main__':

    root = tk.Tk()
    root.geometry("800x800")
    root.resizable(0, 0)

    s = 0

    c = tk.Canvas(root, height=250, width=300, bg="blue")
    c.pack()
    
    arc = c.create_arc(
        10, 50, 240, 210,
        extent=150,
        outline="red",
        fill='red',
        tags=("arc",))
    
    menjajKanvas(arc)
    
    root.mainloop()

You can avoid repeated code in the two functions menjajKanvas, and shrink_arc with the following new function increment_arc described hereunder: However, it makes it more difficult to "get it right" for beginners, and is also maybe less readable for the same reasons.

def increment_arc(arc, increment=-1):
    global s
    if s % 30 != 0:
        delay = 10     # sets short delay if arc not a multiple of 30
    else:
        delay = 1000   # otherwise sets a longer delay
        if s == 0 or s == 180:  # reverse the action when we reach 0, or 180
            increment = - increment
    s  = increment
    c.itemconfig(arc, extent=s, fill="red")
    root.after(delay, increment_arc, arc, increment)

and replace the initial call (menjajKanvas(arc)) with root.after(10, increment_arc, arc)

  • Related