如何使用单选按钮更改时间格式

时间:2014-12-09 20:53:33

标签: python-3.x tkinter

我正在为学校项目制作数字时钟这是我到目前为止的代码(注意单选按钮什么都不做)我一直在尝试我能想到的所有内容,让单选按钮改变时间的显示方式标签,但这就是我现在所有的工作

from tkinter import *
from datetime import *
from time import *

class App():
    def __init__(self):
    self.root = Tk()
    self.root.title('Digital Clock')
    self.label = Label(text="", font= ('times', 40, 'bold'), bg= 'blue')
    self.label.pack()
    self.update_clock()
    self.button1 = Radiobutton(self.root, text='12 hour format', value=1)
    self.button1.pack()
    self.button2 = Radiobutton(self.root, text='24 hour format', value=2)
    self.button2.pack()
    self.root.mainloop()

def get12hour(self):
    now = datetime.now()
    time = now.strftime('%I:%M:%S %p').lstrip('0')
    return time

def get24hour(self):
    now = datetime.now()
    time = now.strftime('%H:%M:%S').lstrip('0')
    return time

def update_clock(self):
    time = self.get12hour()
    self.label.configure(text=time)
    self.root.after(200, self.update_clock)

app=App()

1 个答案:

答案 0 :(得分:1)

您的单选按钮需要共享您可以检查的公共变量。试试这个:

from tkinter import *
from datetime import *
from time import *

class App():
    def __init__(self):
        self.root = Tk()
        self.root.title('Digital Clock')
        self.label = Label(text="", font= ('times', 40, 'bold'), bg= 'blue')
        self.label.pack()

        self.which_button = IntVar()  # share this between all radio buttons in a group
        self.which_button.set(1)  #initialize
        self.update_clock()
        self.button1 = Radiobutton(self.root, variable=self.which_button, 
                                   text='12 hour format', value=1)
        self.button1.pack()
        self.button2 = Radiobutton(self.root, variable=self.which_button, 
                                   text='24 hour format', value=2)
        self.button2.pack()
        self.root.mainloop()

    def get12hour(self):
        now = datetime.now()
        time = now.strftime('%I:%M:%S %p').lstrip('0')
        return time

    def get24hour(self):
        now = datetime.now()
        time = now.strftime('%H:%M:%S').lstrip('0')
        return time

    def update_clock(self):
        time = self.get12hour() if self.which_button.get() == 1 else self.get24hour()
        self.label.configure(text=time)
        self.root.after(200, self.update_clock)

app=App()