如何将标签部件放在彼此相邻的位置?

2024-06-28 18:59:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的GUI程序来测量某个事件的时间。一切都很好,但是有一件事让我恼火-所有标签小部件都在“闪烁”(由于被创建),所以我想重组我的代码,以便我有两个标签组-其中一个将持续显示,另一个(实际测量时间)将闪烁。问题是,当我试图将一个标签拆分为两个较小的标签时,我无法使它正好挨着另一个标签,所以它看起来像这样:

enter image description here

这是我最初的工作代码:

# str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *
from threading import *

def display():

    event, today, str8, seconds, minutes, hours, days, weeks, years = calc()

    Label(root,
          text = "You have been STR8 for:\n",
          font = "Verdana 8 bold").grid(row = 0, sticky = W)

    Label(root,
          text = "Years: "
               + str(round(years, 2)),
          font = "Verdana 8").grid(row = 1, sticky = W)

    Label(root,
          text = "Weeks: "
               + str(round(weeks, 2)),
          font = "Verdana 8").grid(row = 2, sticky = W)

    Label(root,
          text = "Days: "
               + str(round(days, 2)),
          font = "Verdana 8").grid(row = 3, sticky = W)

    Label(root,
          text = "Hours: "
               + str(round(hours, 2)),
          font = "Verdana 8").grid(row = 4, sticky = W)

    Label(root,
          text = "Minutes: "
               + str(round(minutes, 2)),
          font = "Verdana 8").grid(row = 5, sticky = W)

    Label(root,
          text = "Seconds: "
               + str(round(str8.total_seconds())),
          font = "Verdana 8").grid(row = 6, sticky = W)

    Button(root,
           text = "EXIT",
           font = "Verdana 8",
           height = 1,
           width = 19,
           command = quit).grid(row = 7)


def calc():

    event = datetime(2017, 4, 4, 0, 0, 0)
    today = datetime.now()

    str8 = today - event

    seconds = str8.total_seconds()
    minutes = str8.total_seconds() / 60
    hours = minutes / 60
    days = hours / 24
    weeks = days / 7
    years = weeks / 52

    return event, today, str8, seconds, minutes, hours, days, weeks, years


def print_it():
    t = Timer(1.0, print_it)
    calc()
    try:
        display()
    except RuntimeError:
        pass
    else:
        t.start()

def quit():
    root.destroy()

if __name__ == '__main__':
    root = Tk()
    root.title("STR8")
    root.resizable(width = False, height = False)
    print_it()
    root.mainloop()

…在我试着把其中一个分开试一试之前:

^{pr2}$

然后,我将把不断显示的所有标签放入create_widgets()函数中,其他标签留在display()函数中。在

我使用的是python3.5。在


Tags: texteventroot标签labelgridrowseconds
1条回答
网友
1楼 · 发布于 2024-06-28 18:59:26

TKinter有一个名为DoubleVarvariable class,它允许您创建一个变量,用于更新标签小部件。使用这个方法,而不是使用text=作为标签,而是使用textvariable=来引用您已经创建的变量,并且Tk知道在变量值改变时更新标签(尽管应该注意,有其他方法可以实现更新标签,我在这里不详细介绍)。在

在下面的代码中,我们为每个时间单位创建两个文本标签—一个用于告诉用户值与什么相关,另一个用于实际显示值。为了简单起见,我是通过词典来做这件事的。在

然后我们第一次调用increment,它设置所有相关的值。完成此操作后,我们使用self.after(1000, self.increment)在1000毫秒=1秒后运行增量进程。在

# str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *


class App(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.grid(sticky=N + W + E + S)

        Label(self, text='You have been STR8 for:', font="Verdana 8 bold").grid(row=0, sticky=W)

        self.counters = dict()
        measurements = ['Seconds', 'Minutes', 'Hours', 'Days', 'Weeks', 'Years']
        for i, measurement in enumerate(measurements):
            self.counters[measurement] = DoubleVar()
            Label(self, text=measurement, font='Verdana 8').grid(row=i+1, column=0, sticky=W)
            Label(self, textvariable=self.counters[measurement], font='Verdana 8').grid(row=i + 1, column=1, sticky=E)
            self.counters[measurement].set(0)

        Button(self,
               text="EXIT",
               font="Verdana 8",
               height=1,
               width=19,
               command=quit).grid(row=7, column=0)

        self.increment()

    def increment(self):
        event = datetime(2017, 4, 4, 0, 0, 0)
        today = datetime.now()

        str8 = today - event
        self.counters['Seconds'].set(round(str8.total_seconds(), 2))
        self.counters['Minutes'].set(round(str8.total_seconds()/60, 2))
        self.counters['Hours'].set(round(str8.total_seconds() / 3600, 2))
        self.counters['Days'].set(round(str8.total_seconds() / (3600 * 24), 2))
        self.counters['Weeks'].set(round(str8.total_seconds() / (3600 * 24 * 7), 2))
        self.counters['Years'].set(round(str8.total_seconds() / (3600 * 24 * 7 * 52), 2))

        self.after(1000, self.increment)


if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.title("STR8")
    root.resizable(width=False, height=False)
    app.mainloop()

这将产生一个如下所示的窗口:

enter image description here

并且应该每秒钟更新一次而不闪烁。在

相关问题 更多 >