You need to enable JavaScript to run this app. 如何实现Tkinter向MySQL插入数据时每次自动更新当前时间
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Tkinter向MySQL插入数据时每次自动更新当前时间

问题原因
  • 时间计算逻辑位置错误:Time、Date变量的生成逻辑放在了类的__init__构造方法中,仅在程序启动、类实例化时执行1次,后续每次调用addData方法插入数据时,复用的都是程序启动时生成的旧时间值,无法更新为插入时刻的最新时间。
  • 变量作用域不规范:__init__方法中定义的BluetoothAddress、Time、Date都是局部变量,addData方法中无法直接访问,运行时会触发变量未定义的报错。
修复方案

把时间获取逻辑迁移到addData方法内部,同时将跨方法调用的变量改为实例属性(绑定到self),修改后的完整代码如下:

from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import pymysql
from datetime import date, datetime

class DataEntryForm:

    def __init__(self,root):
        self.root = root
        self.root.geometry('600x500+0+0')
        self.root.configure(background='gainsboro')

        # 变量声明为实例属性,跨方法可访问
        self.BluetoothAddress=StringVar()

    def addData(self):
        if self.BluetoothAddress.get()=='':
            tkinter.messagebox.showerror('No Bluetooth Address','Please Enter Bluetooth Address')
        else:
            # 每次插入数据前重新获取当前时间
            curr_time=datetime.now()
            Time=curr_time.strftime('%H:%M:%S')
            Date=date.today()
            
            sqlCon = pymysql.connect(host='localhost',user='root',password='GAEPCI2020',database='heshevo')
            cur = sqlCon.cursor()
            cur.execute("INSERT into datam5 values(%s,%s,%s)",
            (self.BluetoothAddress.get(),
            Time,
            Date))
            sqlCon.commit()
            update() # 若update是类内方法,需要改为self.update()调用
            sqlCon.close()
           #tkinter.messagebox.showinfo('Data Entered Succesfully', 'Bluetooth Address Entered Succesfully')
可选优化方案

你也可以直接在MySQL表设计层面处理时间自动填充,不需要在Python代码中维护时间逻辑:

  1. 将datam5表的时间字段类型修改为TIMESTAMP或DATETIME,设置默认值为CURRENT_TIMESTAMP
  2. 插入SQL语句可以省略时间字段的传值,数据库会自动填充插入时刻的最新时间,避免Python端和数据库端时区不一致导致的时间偏差。

内容的提问来源于stack exchange,提问作者Kyelle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 19:54:05