-1

Here is my code:

from tkinter import *
import time

master=Tk()
w=Canvas(master,width=500,height=500)
w.pack()
line=w.create_line
rect=w.create_rectangle
oval=w.create_oval
poly=w.create_polygon

rect(0,100,500,150,fill="#770077")
for x in range(0,51):
    rect(0,100,x*10,150,fill="#007700")
    w.after(100)

I've tried using the time.sleep() function, but that did not help, so I tried tkinter's wait function, and that didn't do anything either. This is for a class, but no one from the class has any ideas either.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • You can use `w.update()` in your `for` loop or create the rectangle inside a function and use `after(ms, func)`, But if you're trying to make a progress bar then why not use [ttk progress bar](https://www.tcl.tk/man/tcl/TkCmd/ttk_progressbar.htm) and a good illustration of ttk progress bar in this [post](https://stackoverflow.com/questions/7310511/how-to-create-downloading-progress-bar-in-ttk) – Saad May 01 '19 at 16:14
  • First you have to understand [Event-driven programming](https://stackoverflow.com/a/9343402/7414759) – stovfl May 01 '19 at 19:19
  • you can't use `sleep` or `wait` because it stops `mainloop` which does all job - it runs loop which gets mouse/key event from system, sends events to widgets, updates data in widgets, redraw window and widgets. – furas May 01 '19 at 22:16

1 Answers1

0

Create function which draws rectangle using x and which uses after() to run itself again after 100ms with bigger x

import tkinter as tk

def draw_next_rect(x):
    w.create_rectangle(0, 100, x*10, 150, fill="#007700")
    x += 1
    # stop animation with x==51
    if x < 51:
        master.after(100, draw_next_rect, x)

master = tk.Tk()

w = tk.Canvas(master, width=500, height=500)
w.pack()

w.create_rectangle(0, 100, 500, 150, fill="#770077")

# start animation with x=0
draw_next_rect(0)

master.mainloop()

EDIT: similar with ttk.Progressbar

import tkinter as tk
import tkinter.ttk as ttk

def draw_next_rect():
    progressbar.step()
    if progressbar['value'] < 50:
        master.after(100, draw_next_rect)

master = tk.Tk()

progressbar = ttk.Progressbar(master, maximum=50.001, mode='indeterminate')
progressbar.pack()

draw_next_rect()

maximum= has to be little bigger then 50 because for 50 it removes bar when value == maximum master.mainloop()

furas
  • 134,197
  • 12
  • 106
  • 148