首页 > 编程问答 >Tkinter动态标签显示

Tkinter动态标签显示

时间:2024-07-26 14:57:51浏览次数:7  
标签:python tkinter tkinter-layout tkinter-label

我正在研究简单的窗口,喜欢在里面有时钟。了解如何在单独的窗口中动态显示时间: enter image description here

不知何故,放入我的项目中的相同代码仅显示标签的紫色背景:

def time():
    string = strftime('%H:%M:%S %p')
    lbl.config(text=string)
    lbl.after(1000, time)

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        main_frame = tk.Frame(self, height=600, width=1024)
        main_frame.pack_propagate(0)
        main_frame.pack(fill="both", expand="true")
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)

        frame1 = tk.LabelFrame(self, text="Parametry Pracy")
        frame1.place(rely=0.05, relx=0.02, height=400, width=400)


        pp=tk.Frame(frame1)
        pp.pack(pady=2)

        lbl = Label(pp, font=('arial', 20, 'bold'),bg='purple', fg='white', width=11)
        lbl.grid(row=0, column=0, sticky="W", padx=20)

enter image description here


的代码中缺少对 time() 函数的调用。定义了该函数,但从未实际执行过它。这就是为什么的标签只显示紫色背景而没有更新时间的原因。

以下是如何修复代码的方法:

import tkinter as tk
from time import strftime

def time():
    string = strftime('%H:%M:%S %p')
    lbl.config(text=string)
    lbl.after(1000, time)

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        main_frame = tk.Frame(self, height=600, width=1024)
        main_frame.pack_propagate(0)
        main_frame.pack(fill="both", expand="true")
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)

        frame1 = tk.LabelFrame(self, text="Parametry Pracy")
        frame1.place(rely=0.05, relx=0.02, height=400, width=400)

        pp=tk.Frame(frame1)
        pp.pack(pady=2)

        global lbl  # Make lbl accessible from the time function
        lbl = tk.Label(pp, font=('arial', 20, 'bold'),bg='purple', fg='white', width=11)
        lbl.grid(row=0, column=0, sticky="W", padx=20)

        time()  # Start the clock

root = MainWindow()
root.mainloop()

主要更改:

  1. global lbl : 在 time() 函数中使用 global lbl 使函数能够访问并修改在 MainWindow 类中创建的 lbl 变量。

  2. time() 调用 : 在 MainWindow 类的 __init__ 方法中添加 time() 调用,以便在创建窗口后立即启动时钟。

通过这些更改,的时钟现在应该可以正常更新了。

标签:python,tkinter,tkinter-layout,tkinter-label
From: 78790596

相关文章

  • 用Python解析邮件日志
    我的任务有点困难。我有一个邮件日志,如:Oct315:30:18mail1postfix/lmtp[5369]:DB10242054:to=<XXXXX>,orig_to=<XXXXXX>,relay=ip[ip]:port,delay=1.4,delays=0.04/0/0.01/1.4,dsn=2.0.0,status=sent(2502.0.0fromMTA(smtp:[iP]:port):2502.0.0Ok:queueda......
  • Python,Pyinstaller打包含taichi模块的程序
    Python版本3.9、taichi版本1.7.1,pyinstaller版本6.9.0问题描述:正常Pyinstaller打包后报错[Taichi]version1.7.1,llvm15.0.1,commit0f143b2f,win,python3.9.19[Taichi]Startingonarch=x64Traceback(mostrecentcalllast):File"taichi\lang\_wrap_inspec......
  • Python,运行Yolo项目,报错AttributeError: ‘ImageDraw‘ object has no attribute ‘te
    Python3.9问题描述:其他电脑已经运行成功的Python,YOLO代码到我电脑上运行报错Traceback(mostrecentcalllast): File"C:\Users\Administrator\Desktop\20240725\识别项目\predict.py",line122,in<module>  frame=np.array(yolo.detect_image(frame)) Fil......
  • Python从零开始制做文字游戏(荒岛求生)
    文章目录前言开发游戏《荒岛求生》游戏大纲背景内容通关条件游戏过程探索荒岛购买物资休息总结代码开发定义变量当前代码引入背景故事当前代码循环问题解决:函数当前代码制作延时当前代码制作a函数(探索荒岛阶段)展示数......
  • 使用 Python 进行数据分析:入门指南
    使用Python进行数据分析:入门指南1.简介本指南将介绍如何使用Python进行数据分析,涵盖从数据加载到可视化分析的各个方面。2.必要的库NumPy:用于数值计算和数组操作。Pandas:用于数据处理和分析,提供DataFrame结构。Matplotlib:用于数据可视化,创建各种图表。Seab......
  • IT实战课堂计算机毕业设计源码精品基于Python的高校教育教材采购出入库进销存储信息管
    项目功能简介:《[含文档+PPT+源码等]精品基于Python的高校教育教材信息管理系统设计与实现》该项目含有源码、文档、PPT、配套开发软件、软件安装教程、项目发布教程、包运行成功以及课程答疑与微信售后交流群、送查重系统不限次数免费查重等福利!软件开发环境及开发工具:开......
  • 为什么我的 Python 脚本失败并出现 TypeError?
    我正在编写一个Python脚本,该脚本应该计算数字列表的总和。但是,当我运行代码时遇到TypeError这是一个最小的例子:numbers=[1,2,3,'4']total=sum(numbers)print(total)Theerrormessageis:TypeError:unsupportedoperandtype(s)for+:'int'and'str......
  • 如何通过socks代理传递所有Python的流量?
    有如何通过http代理传递所有Python的流量?但是,它不处理sock代理。我想使用sock代理,我们可以通过ssh隧道轻松获得它。ssh-D5005user@server你可以使用socks库,让你的Python代码通过SOCKS代理传递所有流量。这个库可以让你在套接字级别上指定代......
  • 如何在streamlit python中流式传输由LLM生成的输出
    代码:fromlangchain_community.vectorstoresimportFAISSfromlangchain_community.embeddingsimportHuggingFaceEmbeddingsfromlangchainimportPromptTemplatefromlangchain_community.llmsimportLlamaCppfromlangchain.chainsimportRetrievalQAimports......
  • python mysql操作
    pipinstallmysql-connector-pythonimportmysql.connector#配置数据库连接参数config={'user':'your_username','password':'your_password','host':'your_host','database'......