You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter类中嵌套函数my_upd无法执行的问题求助

问题解决方法

核心问题原因

代码中创建了两个Tk()实例(主窗口self.mainw = Tk()和报告窗口self.my_win = tk.Tk()),但tkinter规定一个程序只能有一个主Tk实例。多个Tk实例会导致事件循环冲突,使得DateEntry的变量追踪回调my_upd无法正常响应。

修复步骤

  1. 将报告窗口从tk.Tk()改为tk.Toplevel(self.mainw),让它作为主窗口的子窗口,共享同一个事件循环。
  2. 移除报告窗口中的self.my_win.mainloop(),主窗口已经在运行事件循环,重复调用会导致阻塞和冲突。

修改后的完整代码

from tkinter import *
class Main:
    def __init__(self):
        self.mainw = Tk()
        self.mainw.title("Daily sales report")
        width = 1000
        height = 700
        screen_width = self.mainw.winfo_screenwidth()
        screen_height = self.mainw.winfo_screenheight()
        x = (screen_width / 2) - (width / 2)
        y = (screen_height / 2) - (height / 2)
        self.mainw.geometry("%dx%d+%d+%d" % (width, height, x, y))
        self.mainw.resizable(0, 0)
        self.frame = Frame(self.mainw, width=1000, height=700, bg="#FFFFFF")
        self.frame.place(x=0, y=0)
        self.frameinfo = self.frame.place_info()
        self.reportbut = Button(self.frame, text="Report_But", font="roboto 14", bd=5, width=8, bg="#FFFFFF",
                                command=self.report)
        self.reportbut.place(x=10, y=5, height=40, width = 200)
    def report(self):
        import tkinter as tk
        from tkinter import ttk
        from tkcalendar import DateEntry
        import sqlite3
        # 将Tk()替换为Toplevel,关联主窗口
        self.my_win = tk.Toplevel(self.mainw)
        self.my_win.geometry("1350x800")
        self.my_win.title("Christ the light limitd")
        self.sel = tk.StringVar()
        self.cal = DateEntry(self.my_win, selectmode='day', textvariable=self.sel)
        self.cal.grid(row=0, column=0, padx=20, pady=30)
        def my_upd(*args):
            if (len(self.sel.get()) > 4):
                date = self.cal.get_date()
                date1 = date.strftime('%y-%m-%d')
                date2 = date.strftime("%d-%B-%Y")
                self.le1.config(text=date2)
                conn = sqlite3.connect(r'E:\report.db')
                c = conn.cursor()
                query = ("select * from sales where Date = :d")
                # 修正参数传递方式,匹配占位符:d
                c.execute(query, {"d": date1})
                saleslist = c.fetchall()
                for item in self.trv.get_children():
                    self.trv.delete(item)
                total = 0
                for data in saleslist:
                    self.trv.insert("", 'end', iid=data[0], text=data[0],
                                    values=(data[0], data[1], data[2], data[3], data[4], data[5], data[6]))
                    total = round(total + (data[5]), 2)
                self.le2.config(text="Total: " + str(total) + "ssp")
                # 关闭数据库连接,避免资源泄漏
                conn.close()
        self.le1 = tk.Label(self.my_win, font=('Times', 22, 'bold'), fg='blue')
        self.le1.grid(row=0, column=1)
        self.trv = ttk.Treeview(self.my_win, selectmode='browse')
        self.trv.grid(row=1, column=1, padx=20, pady=20)
        self.trv["columns"] = ("1", "2", "3", "4", "5", "6", "7")
        self.trv['height'] = 20
        self.trv['show'] = 'headings'
        self.trv.column("1", width=100, anchor='c')
        self.trv.column("2", width=100, anchor='c')
        self.trv.column("3", width=100, anchor='c')
        self.trv.column("4", width=100, anchor='c')
        self.trv.column("5", width=100, anchor='c')
        self.trv.column("6", width=100, anchor='c')
        self.trv.column("7", width=100, anchor='c')
        self.trv.heading("1", text="Transaction ID")
        self.trv.heading("2", text="Invoice No.")
        self.trv.heading("3", text="Product ID")
        self.trv.heading("4", text="Description")
        self.trv.heading("5", text="Quantity")
        self.trv.heading("6", text="Total Price")
        self.trv.heading("7", text="Date")
        self.sel.trace('w', my_upd)
        self.le2 = tk.Label(self.my_win, font=('Times', 22, 'bold'), fg='red')
        self.le2.grid(row=1, column=2, sticky='ne', pady=20)
w=Main()
w.mainw.mainloop()

额外修正了两处细节问题:

  • 数据库查询的参数传递方式,原代码的元组参数无法匹配:d占位符,改为字典传递确保匹配正确。
  • 添加了数据库连接关闭语句,避免长期占用资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:10:30