Displaying time in tkinter label - python

I am trying to get the current time to show and update every second in a tkinter label.
Im assuming that i am doing this completely wrong. Im rather new to this and trying to work through it bit by bit.
from tkinter import *
import sys
import time
#function to close window when ESC is pressed
def close(event):
sys.exit()
def curtime():
while 1==1:
current_time = time.strftime('%H:%M:%S')
print(current_time)
time.sleep(1)
#Main System
window = Tk()
window.state('zoomed')
window.configure(bg='#3a3a3a')
#Frames
top_frame = Frame(window)
top_frame.pack(side=TOP)
bottom_frame = Frame(window)
bottom_frame.pack(side=BOTTOM)
#Labels
header_label = Label(top_frame, text="SARA", background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
header_label.pack(side=LEFT)
header_label2 = Label(top_frame, textvariable = curtime(), background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
header_label2.pack(side=LEFT)
#on press ESC window closes
window.bind('<Escape>', close)
window.mainloop()

#function to get timer to calculate
def timer():
timer_tick = strftime("%I:%M:%S")
time_label.configure(text=timer_tick)
time_label.after(1000, timer)
time_label = Label(top_frame, background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
time_label.pack(side=LEFT)
#if statement which constantly returns true to make the timer refresh and tick
if __name__ == "__main__":
timer()

Related

Call a fonction from message box Tkinter

I want to call the fonction (submit) after clicking on the message box. With this code I have to reclick on button everytime after the messagebox but would appreciate if the timer launch automatically after clicking on the message box.
If anyone have a clue I will appreciate.
The following code :
import time
from tkinter import *
root = Tk()
root.resizable(width=False, height=False)
root.geometry("300x250")
root['background']='#39E5F9'
root.title("Time To Drink Water")
minute = StringVar()
second = StringVar()
minute.set("45")
second.set("00")
minuteEntry = Entry(root, width=3, font=("Arial", 35, ""),
textvariable=minute,justify='center')
minuteEntry.place(x=50, y=60)
secondEntry = Entry(root, width=3, font=("Arial", 35, ""),
textvariable=second,justify='center')
secondEntry.place(x=170, y=60)
def submit():
# stored in here : 2700 = 45 mins
temp = 2700
while temp > -1:
# divmod(firstvalue = temp//60, secondvalue = temp%60)
mins, secs = divmod(temp, 60)
if mins > 60:
hours, mins = divmod(mins, 60)
minute.set("{0:2d}".format(mins))
second.set("{0:2d}".format(secs))
root.update()
time.sleep(1)
if (temp == 0):
messagebox.showinfo("Time Countdown", "Time To Drink !")
temp -= 1
def go():
btn = Button(root, text='Goodbye dehydration!', bd='6',
command=submit)
btn.place(x=90, y=160)
go()
root.mainloop()
messagebox is waiting for your click so you can run submit() after messagebox and it will run it after clicking in messagebox
But you shouldn't use while and sleep because it may freeze GUI (in any framework, and in any language). You can use root.after(1000, function) to run function again after 1000ms (1s) and it will work as sleep and while together.
import time
import tkinter as tk # PEP8: `import *` is not preferred
from tkinter import messagebox
# --- functions --- # PEP8: all functions before main code
def submit():
update_counter(2700)
def update_counter(temp):
if temp > -1: # `if` instead of `while` because `after` will work as loop
# divmod(firstvalue = temp//60, secondvalue = temp%60)
mins, secs = divmod(temp, 60)
if mins > 60:
hours, mins = divmod(mins, 60)
minute.set("{:02d}".format(mins)) # use `:02` to get `09` instead of ` 9` (with space)
second.set("{:02d}".format(secs))
temp -= 1
root.after(1000, update_counter, temp) # run again after 1000ms
else:
messagebox.showinfo("Time Countdown", "Time To Drink !")
root.after(0, update_counter, 2700) # run again after 0ms
#update_counter(2700) # run again
# --- main --- # PEP8: `lower_case_names` for variables
running = False
temp = 2700
root = tk.Tk()
minute = tk.StringVar(root)
second = tk.StringVar(root)
minute.set("45")
second.set("00")
minute_entry = tk.Entry(root, width=3, textvariable=minute, font=("Arial", 35, ""), justify='center')
minute_entry.grid(row=0, column=0)
second_entry = tk.Entry(root, width=3, textvariable=second, font=("Arial", 35, ""), justify='center')
second_entry.grid(row=0, column=1)
btn = tk.Button(root, text='Goodbye dehydration!', command=submit)
btn.grid(row=1, column=0, columnspan=2)
root.mainloop()
PEP 8 -- Style Guide for Python Code
There is other problem. You can click button two times and it will run two update_counter() at the same time. It may need to disable button, or you would have to use boolean variable - ie. running = False - to control if it has to run update_counter() or not.

How do I fix "name is not defined error" (tkinter)

I'm trying to make a stopwatch app with Tkinter, but now I have some trouble. Somewhy, I'm receiving the following error:
name 'label13' is not defined. line 177, in countdown
label13.config(text = count)
I have no idea why this error message pops up. I really appreciate it if you can help me.
Here is my code:
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from tkinter import *
window = Tk()
window.geometry("703x981")
window.configure(bg = "#FFFFFF")
def countdown(count):
#change text in label
label13.config(text = count)
if count > 0:
#call countdown again after 1000ms (1s)
window.after(1000, countdown, count-1)
countdown(120)
label13 = Label(window, font = "Courier 40 bold", bg="white", fg="black")
label13.place(x =29, y=300)
window.resizable(False, False)
window.mainloop()
Because label13 should defined before calling countdown(120) as shown below.
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from tkinter import *
window = Tk()
window.geometry("703x981")
window.configure(bg = "#FFFFFF")
window.resizable(False, False)
label13 = Label(window, font = "Courier 40 bold", bg="white", fg="black")
label13.place(x =29, y=300)
def countdown(count):
#change text in label
label13.config(text = count)
if count > 0:
#call countdown again after 1000ms (1s)
window.after(1000, countdown, count-1)
countdown(120)
window.mainloop()

after_cancel doesn't work in python tkinter

I made a simple countdown in my trivia game and every time that I go to the next slide it doesn't cancel the previous countdown timer and overlaps with the previous one.
I searched about that on the web and found the after_cancel function that cancels the timer after I go to the next slide and then I recreate it. But it still overlaps even after I added this function.
I think that I didn't give the after_cancel the correct arguments.
from tkinter import *
window = Tk()
window.attributes('-fullscreen',True)
WaitState = StringVar()
count = 10
button_label = StringVar()
def clear():
WaitState.set(1)
for widgets in window.winfo_children():
widgets.destroy()
def clear_time():
clear()
time_up_label = Label(
window,
text="Time is up",
bg = "#6378ff",
fg="#000000",
font=("Arial", 100,"bold"))
time_up_label.place(relx = 0.5,rely = 0.5,anchor = 'center')
continue_but = Button(
window,
text="Continue",
font=("Knewave",25,"bold"),
bg="#942222",
width=11,
height=5,
command=clear)
continue_but.place(relx = 1.0,rely = 1.0,anchor =SE)
continue_but.wait_variable(WaitState)
def button_countdown(i, label):
if i > 0:
i -= 1
label.set(i)
window.after_id = window.after(1000, lambda: button_countdown(i, label))
else:
window.after_cancel(window.after_id)
clear_time()
for index in range(5):
continue_but = Button(
window,
text="Continue",
font=("Knewave",25,"bold"),
bg="#942222",
width=11,
height=5,
command=clear)
continue_but.place(relx = 1.0,rely = 1.0,anchor =SE)
button_label.set(count)
timer_label = Label(
window,
textvariable=button_label,
bg="#6378ff",
fg="#ff0000",
font=("Arial",46,"bold"))
timer_label.pack()
button_countdown(count, button_label)
continue_but.wait_variable(WaitState)
window.mainloop()

How do I make btn01 or btn go to a random spot every 4 milliseconds and when you click on it it will stop and do something else?

I want to make any btn go to a random spot every 3 milisecounds, and when you click the random button it will do something else like print Hi and stop the button from moving.
Here is the code:
I tried while a == True: but it keeps frezzing when i press the "To make a video" button and just frezzes for a while
import time
import os
import tkinter as tk
import random
from tkinter import *
from tkinter import messagebox
from tkinter import Button
import math
from tkinter import Text
from tkinter import Grid
from tkinter import Place
#from tkinter import place
window = tk.Tk()
window.title("There is no game")
window.geometry("494x300")
numberx = random.randint(1,200)
numbery = random.randint(1,200)
##def clickedrandom():
## a = False
def toplayagame():
print("Hi")
a = True
def tomakeavideo():
T.delete('1.0', END)
T.insert(tk.END, "People who are watching go hit that subscribe button and hit that like button also hit that little bell to turn on notifcations")
T.configure(width = 25, height=6)
while a == True:
numberx = random.randint(1,200)
numbery = random.randint(1,200)
int(numberx)
int(numbery)
time.sleep(0.3)
btn.place(x = numberx, y = numbery)
def pressed():
T.delete('1.0', END)
T.insert(tk.END, "Why are you here?")
btn.place(x=190, y=200)
T.configure(width = 17, height=1)
btn.configure(text = "To play a game", width=12,command=toplayagame)
btn1= Button(window, bd=10,text="To make a video",activebackground='White',activeforeground='Black',bg='Grey',fg='White',height=1,width=15,state=ACTIVE,command=tomakeavideo)
btn1.pack()
btn1.place(x=1,y=200)
T = tk.Text(window, height=1, width=10)
T.pack()
T.insert(tk.END, "Hello user")
btn = Button(window, bd=10,text="Hello",activebackground='Black',activeforeground='White',bg='Grey',fg='White',height=1,width=4,state=ACTIVE,command=pressed)
btn.pack()
btn.place(x=215, y=200)
window.mainloop()
Use the <tkinter widget>.after(<time>, <function>) like this:
import tkinter as tk
import random
playing_game = False
def to_make_video():
global btn1
msg = "People who are watching go hit that subscribe button and"+\
" hit that like button also hit that little bell to turn on"+\
" notifcations"
text_widget.delete("0.0", "end")
text_widget.insert("end", msg)
text_widget.configure(width=25, height=6)
btn1.destroy()
start_game()
def game_won():
# When the button is pressed:
global playing_game
playing_game = False
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why aren't you leaving?")
text_widget.configure(width=23, height=1)
btn.destroy()
def move_button():
global playing_game
# If the game is over stop moving the button
if not playing_game:
return None
# Pick the next random position for the button
numberx = random.randint(1, 200)
numbery = random.randint(1, 200)
btn.place(x=numberx, y=numbery)
# After 500 milliseconds call `move_button` again
# You can change the value to make it faster/slower
root.after(500, move_button)
def start_game():
# Start the game
global playing_game
btn.config(command=game_won)
playing_game = True
# Start the loop that keeps moving it to new random positions
move_button()
def pressed():
global btn1
# Ask the user why they are here
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why are you here?")
text_widget.configure(width=17)
btn.place(x=190, y=200)
btn.configure(text="To play a game", width=12, command=lambda: None)
btn1 = tk.Button(root, bd=10, text="To make a video", bg="grey", fg="white",
activebackground="white", activeforeground="black",
height=1, width=15, command=to_make_video)
btn1.place(x=1, y=200)
# Create a window
root = tk.Tk()
root.geometry("310x250")
text_widget = tk.Text(root, height=1, width=10)
text_widget.pack()
text_widget.insert(tk.END, "Hello user")
btn = tk.Button(root, bd=10, text="Hello", activebackground="black",
activeforeground="white", bg="grey", fg="white", height=1,
width=4, command=pressed)
btn.place(x=215, y=200)
# Run tkinter's mainloop
root.mainloop()

How to make a Tkinter window not resizable?

I need a Python script that uses the Tkinter module to create a static (not resizable) window.
I have a pretty simple Tkinter script but I don't want it to be resizable. How do I prevent a Tkinter window from being resizable? I honestly don't know what to do.
This is my script:
from tkinter import *
import ctypes, os
def callback():
active.set(False)
quitButton.destroy()
JustGo = Button(root, text=" Keep Going!", command= lambda: KeepGoing())
JustGo.pack()
JustGo.place(x=150, y=110)
#root.destroy() # Uncomment this to close the window
def sleep():
if not active.get(): return
root.after(1000, sleep)
timeLeft.set(timeLeft.get()-1)
timeOutLabel['text'] = "Time Left: " + str(timeLeft.get()) #Update the label
if timeLeft.get() == 0: #sleep if timeLeft = 0
os.system("Powercfg -H OFF")
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
def KeepGoing():
active.set(True)
sleep()
quitButton1 = Button(root, text="do not sleep!", command=callback)
quitButton1.pack()
quitButton1.place(x=150, y=110)
root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')
timeLeft = IntVar()
timeLeft.set(10) # Time in seconds until shutdown
active = BooleanVar()
active.set(True) # Something to show us that countdown is still going.
label = Label(root, text="ALERT this device will go to sleep soon!", fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
label.pack()
timeOutLabel = Label(root, text = 'Time left: ' + str(timeLeft.get()), background='light blue') # Label to show how much time we have left.
timeOutLabel.pack()
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()
quitButton.place(x=150, y=110)
root.after(0, sleep)
root.mainloop()
The resizable method on the root window takes two boolean parameters to describe whether the window is resizable in the X and Y direction. To make it completely fixed in size, set both parameters to False:
root.resizable(False, False)

Categories

Resources