Using .config In Tkinter
Solution 1:
Use after
instead of while
and wait
. Also, you were subtracting a second as soon as your clock begins. Send the subtracted value to the next call instead. If all you are going to do is stick every widget on the next row
in one column
then you don't have to be specific in grid()
, you just have to make sure you call grid
on the widgets in the proper order. If you add more columns the rules change back to how you were doing it.
import time
import tkinter as tk
root = tk.Tk()
root.geometry('150x100')
defcountdown_clock(s, t):
ifnot s:
t.configure(text='time!')
return
t.configure(text=s)
root.after(1000, countdown_clock, s-1, t)
time_lbl = tk.Label(root, text='00', font=20)
time_lbl.grid()
start_btn = tk.Button(root, text='start', command=lambda: countdown_clock(int(seconds_ent.get()), time_lbl))
start_btn.grid()
seconds_ent = tk.Entry(root)
seconds_ent.grid()
root.mainloop()
Solution 2:
while
loops, leads to windows being unresponsive after sometime, so the best way is to get rid of that and use the inbuilt, after()
method.
Here is a working example:
import time
import tkinter as tk
root = tk.Tk()
root.geometry('150x100')
seconds_inp = tk.Entry(root)
time_label = tk.Label(root, text='00', font=20)
start_button = tk.Button(
root, text='start', command=lambda: countdown_clock(int(seconds_inp.get())))
def countdown_clock(seconds):
seconds = seconds -1
time_label.config(text=seconds)
call= root.after(1000, countdown_clock, seconds)
if seconds ==0:
root.after_cancel(call)
time_label.config(text='Time up!!')
print(seconds)
time_label.grid(row=1, column=0)
start_button.grid(row=2, column=0)
seconds_inp.grid(row=3, column=0)
root.mainloop()
All i did was,I removed the while
because it will interrupt the mainloop()
method, so then i used after()
method to call the function continuously till second
reaches 0, and then i cancel the after()
and finally update the label. And i removed global
outside the functions as those are pointless to be called outside functions.
Hope this cleared your doubt.
Cheers
Post a Comment for "Using .config In Tkinter"