Python Forum

Full Version: How to adjust time - tkinter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everbody,

please help me to solve one issue with my tkinter clock. Time is imported from my cpu but sometimes I need to shift few seconds down or up, so I created buttons with command functions, the problem is that i donĀ“t know how to set the def or those buttons properly (with print function, or transfor string to int and back?), Thanks for any advice. Bellow you can see code:

import sys, random
from tkinter import *
from tkinter import ttk

import time

 
def tick():
    time_string=time.strftime('%H:%M:%S')
    clock.config(text=time_string)
    clock.after(200,tick)
    
root=Tk()

def callback():
    time_string=time.strftime(chr('%H:%M:%S'))

button1=ttk.Button(root, text="Add a second", command=callback)

def call():
    print("down")
button2=ttk.Button(root, text="Remove a sec", command=call)
clock=Label(root, font=("times", 120, "bold"), bg="green")
button1.grid(row=1, column=1)
button2.grid(row=2, column=1)
clock.grid(row=0, column=1)
tick()
root.mainloop()
import datetime
import tkinter as tk
from tkinter import ttk


class MainFrame(tk.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.clock_offset = 0
        self.create_widgets()
        self.layout_widgets()
        self.tick()

    def create_widgets(self):
        self.clock = tk.Label(self.master, font=(
            "times", 120, "bold"), bg="green")
        self.button1 = ttk.Button(
            self.master, text="Add a second", command=self.on_add)
        self.button2 = ttk.Button(
            self.master, text="Remove a sec", command=self.on_remove)

    def layout_widgets(self):
        self.clock.grid(row=0, column=1)
        self.button1.grid(row=1, column=1)
        self.button2.grid(row=2, column=1)

    def tick(self):
        datetime_now = datetime.datetime.now()
        datetime_offset = datetime_now + datetime.timedelta(seconds=self.clock_offset)
        time_string = datetime_offset.strftime('%H:%M:%S')
        self.clock.config(text=time_string)
        self.after(1000, self.tick)

    def on_add(self):
        self.clock_offset += 1

    def on_remove(self):
        self.clock_offset -= 1


root = tk.Tk()
MainFrame(None)
root.mainloop()