Working with previous cases
import time
count = 5
while true:
time.sleep()
count -= 1
Event driven graphical user program
- Working with graphical user interface is a little bit different. It needs to keep watching the screen to see whether if a user clicks on a button.
- It's basically going to refresh and keep listening for events. So every fraction of a second, it's going to keep checking, did something happened did, and the moment when it does, then it's got to react.
- In this case, we tend to call these types of GUI programs event-driven
- The way that it's driven is through our main loop. it's basically looping through and every millisecond it's checking to see did something happen
- window.after It's a method that takes an amount of time that it should wait and then after that amount of time, it simply calls a particular function that you tell it to call passing in any arguments that you want to give it.
#1
#you can see that after 1000 milliseconds, basically one second,
#it calls this function, say_something, and it passes this hello as the input
#to that function.
def say_something(thing):
print(thing)
window.after(1000, say_something, "Hello")
--------------------------------------
Hello
#2
#you can have an infinite amount of positional arguments.
def say_something(a, b, c):
print(a)
print(b)
print(c)
window.after(1000, say_something, 3, 5 ,8)
--------------------------------------
3
5
8
Countdown
def count_down(count):
if count > 0:
window.after(1000, count_down, count - 1)
count_down(5)
-------------
5
4
3
2
1
0
- To change a canvas element, you actually have to tap into the particular canvas you want to change and Then you call a method called itemconfig.
- In this method, you pass in the particular item that you actually want to configure, so in our case it's the timer_text
- Then you pass in the thing about it that you actually want to change in terms of a kwarg, so this is a keyword argument. We're going to change the text to the current count (text=count).
def count_down(count):
canvas.itemconfig(timer_text, text=count)
if count > 0:
window.after(1000, count_down, count - 1)
Start Timer as min:sec
- math.floor, is going to return the largest whole number that is less than or equal to x.
def start_timer():
count_down(5*60)
# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #
def count_down(count):
count_min = math.floor(count/60)
count_sec = count % 60
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
window.after(1000, count_down, count - 1)