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

Tkinter开发CreateEntry类无法调用single_entry外entry_c属性报错问题

问题修复方案

错误原因

  1. 所有调用double_entry方法创建的CreateEntry实例从未执行过single_entry,因此实例本身不存在entry_c属性,但naccheck方法默认所有实例都有该属性,直接调用就会抛出属性不存在的错误。
  2. 你的业务逻辑是希望velocity对应的复选框控制另一个步数输入项的entry_c,但目前每个实例的回调只会操作自身属性,根本拿不到步数输入对应的实例引用,逻辑本身不成立。

修复代码

1. 修改modules文件中CreateEntry类

class CreateEntry(tk.Frame):
    # 新增control_entry_instance参数,用于接收要控制的步数输入实例
    def __init__(self, parent, values, row, bg=None, control_entry_instance=None, **kwargs):
        if bg is None:
            bg = parent['bg']
        super().__init__(parent, bg=bg, **kwargs)
        self.parent = parent
        self.values = values
        self.row = row
        self.control_entry_instance = control_entry_instance

    # double_entry、labels_entry、single_entry方法不需要改动,直接保留原有代码即可

    def naccheck(self):
        if self.nac.get() == 0:
            self.variable2.set(self.variable1.get())
            self.entry_c2.configure(state='disabled')
            # 仅当存在要控制的实例、且该实例有entry_c属性时才操作
            if self.control_entry_instance and hasattr(self.control_entry_instance, 'entry_c'):
                self.control_entry_instance.variable.set('0')
                self.control_entry_instance.entry_c.configure(state='disabled')
        else:
            self.entry_c2.configure(state='normal')
            if self.control_entry_instance and hasattr(self.control_entry_instance, 'entry_c'):
                self.control_entry_instance.entry_c.configure(state='normal')

    def _accept(self, event):
        """Accept value change when a key is released"""
        # 新增属性判断,避免single_entry实例报错
        if hasattr(self, 'nac'):
            if self.nac.get() == 0:
                self.values[-1] = self.entry_c1.get()
            else:
                self.values[-1] = self.entry_c2.get()
        else:
            self.values[-1] = self.entry_c.get()

2. 修改主程序调用逻辑

import modules as md
import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    dictionary = md.create_input_dictionary()
    step_instance = None
    items = list(dictionary.items())
    
    # 先创建步数对应的输入实例(对应你示例里的k3,实际使用替换成你步数项的key)
    for index, (key, values) in enumerate(items):
        if key == 'k3':
            step_instance = md.CreateEntry(root, values, index)
            step_instance.single_entry()
        else:
            # 将步数实例传给velocity对应的输入对象(示例中k1/k2对应velocity类项,可根据实际筛选)
            obj = md.CreateEntry(root, values, index, control_entry_instance=step_instance)
            if md.arenumbers(values[-2]) and md.arenumbers(values[-1]):
                obj.double_entry()
            else:
                obj.labels_entry()

    root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:00