簡體   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