【问题标题】:Frame object has no attribute框架对象没有属性
【发布时间】:2020-02-10 18:42:37
【问题描述】:

我正在构建的 GUI 程序的一部分需要能够将给定的时间转换为秒。我的 GUI 中执行此操作的框架类给我带来了一些麻烦。我创建了一个组合框类型的实例变量来保存要转换的时间段类型的选项。我绑定了组合框选择以将输入时间转换为秒。我想将输入值绑定到输入框中以执行相同的操作。我试图在输入框的验证命令函数中调用我的转换函数,但它告诉我我的框架对象“PERIODIC”没有属性“period_type”。我很困惑,因为我将组合框命名为实例变量,并且类中的所有内容都应该可以访问它。 “self.period_type”就在我的初始化中。为什么我不能访问这个变量?我是否遗漏了一些非常明显的东西?

我得到的 Traceback 是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\4D_User\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/PycharmProjects/LoggerProject/Scripts/ProblemExample.py", line 37, in ValidateTime
    self.convert_time(self.period_type.get())
AttributeError: 'PERIODIC' object has no attribute 'period_type'<

这是我的代码:

from tkinter import ttk
import re

root = tk.Tk()

class PERIODIC(tk.Frame):
    def __init__(self, container, **kwargs):
        super().__init__(container, **kwargs)
        self.time_unconverted = tk.DoubleVar()
        self.time_converted = tk.DoubleVar()
        self.periodic_label = tk.Label(self, text="PERIODIC")
        self.periodic_label.grid(row=0, columnspan=2, sticky="NSEW")
        trigger_option_label = ttk.Label(self, text="Trigger Every: ")
        trigger_option_label.grid(row=1, column=0)
        vcmd = (self.register(self.ValidateTime), '%P')
        self.num_period = tk.Entry(self,textvariable=self.time_unconverted, validate="key", validatecommand=vcmd)
        self.num_period.grid(row=1, column=1)
        self.period_type = ttk.Combobox(self, values=["seconds", "minutes", "hours", "days"])
        self.period_type.bind("<<ComboboxSelected>>", lambda y: self.convert_time(self.period_type.get()))
        self.period_type.grid(row=1, column=2)

    def convert_time(self, type):
        if type == 'seconds':
            self.time_converted.set(self.time_unconverted.get())
        if type == 'minutes':
            self.time_converted.set(self.time_unconverted.get() * 60)
        if type == 'hours':
            self.time_converted.set(self.time_unconverted.get() * 3600)
        if type == 'days':
            self.time_converted.set(self.time_unconverted.get() * 86400)


    def ValidateTime(self, P):
        test = re.compile('^[0-9]{1,3}?\.?[0-9]?$')
        if test.match(P):
            self.convert_time(self.period_type.get())
            return True
        else:
            return False

frame = PERIODIC(root)
frame.grid(row=0,column=0)
root.mainloop()

【问题讨论】:

    标签: python python-3.x tkinter combobox tkinter-entry


    【解决方案1】:

    您的验证命令在您创建条目时被触发,并且它正在使用尚未定义的self.period_type

    简单的解决方案是在创建条目之前移动组合框的创建。

    【讨论】:

    • 非常感谢!立即工作。我对此还是很陌生,所以我没有检查程序执行顺序的问题,没有“分配前引用”错误。应有的教训。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2018-03-30
    • 2017-08-11
    • 2016-06-30
    • 2016-12-30
    • 2021-04-28
    相关资源
    最近更新 更多