A GUI program normally uses an event-driven execution model. That means you build the GUI, and it sits in a loop waiting for events to happen, which it responds to. But in your program there's an infinite while
loop, so the GUI doesn't get a chance to do anything.
There are better ways to do this, but here's a repaired version of your code with minimal changes.
It's not a good idea to use time.sleep
in a GUI program because that puts everything to sleep, so the GUI can't respond to events. In Tkinter, you can call a function periodically using the .after
method.
import tkinter as tk
hours = int(input("what hour is it? "))
minutes = int(input("what minute is it? "))
seconds = int(input("what second is it? "))
window = tk.Tk()
texthours = tk.Text(window, width=2, height=1)
textminutes = tk.Text(window, width=2, height=1)
textseconds = tk.Text(window, width=2, height=1)
texthours.pack(side=tk.LEFT)
textminutes.pack(side=tk.LEFT)
textseconds.pack(side=tk.LEFT)
def show_time():
global hours, minutes, seconds
texthours.delete(0.0, tk.END)
textminutes.delete(0.0, tk.END)
textseconds.delete(0.0, tk.END)
texthours.insert(tk.END, hours)
textminutes.insert(tk.END, minutes)
textseconds.insert(tk.END, seconds)
seconds = seconds + 1
if seconds == 60:
minutes = minutes + 1
seconds = 0
if minutes == 60:
hours = hours + 1
minutes = 0
if hours == 24:
hours = 0
window.after(1000, show_time)
window.after(1000, show_time)
window.mainloop()
Here's a slightly better version, which wraps everything up into a class, so we don't need to use global
. This involves a little more typing, but it makes things more manageable, especially in large complex GUIs.
import tkinter as tk
class Clock:
def __init__(self):
self.hours = int(input("what hour is it? "))
self.minutes = int(input("what minute is it? "))
self.seconds = int(input("what second is it? "))
self.window = tk.Tk()
self.texthours = tk.Text(self.window, width=2, height=1)
self.textminutes = tk.Text(self.window, width=2, height=1)
self.textseconds = tk.Text(self.window, width=2, height=1)
self.texthours.pack(side=tk.LEFT)
self.textminutes.pack(side=tk.LEFT)
self.textseconds.pack(side=tk.LEFT)
self.window.after(1000, self.show_time)
self.window.mainloop()
def show_time(self):
self.texthours.delete(0.0, tk.END)
self.textminutes.delete(0.0, tk.END)
self.textseconds.delete(0.0, tk.END)
self.texthours.insert(tk.END, self.hours)
self.textminutes.insert(tk.END, self.minutes)
self.textseconds.insert(tk.END, self.seconds)
self.seconds += 1
if self.seconds == 60:
self.minutes += 1
self.seconds = 0
if self.minutes == 60:
self.hours += 1
self.minutes = 0
if self.hours == 24:
self.hours = 0
self.window.after(1000, self.show_time)
Clock()