繁体   English   中英

框架对象没有属性

[英]Frame object has no attribute

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

我得到的回溯是:

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()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM