Python Tkinter中AttributeError: 'UICreation'对象无tabControl属性求助
Let's break down what's going wrong here and how to fix it:
The Root Cause
In your __init__ method, you're creating tabControl, tab1, and tab2 as local variables instead of instance attributes of the UICreation class. Local variables only exist within the scope of the method they're defined in—so when you try to access self.tabControl in tabCreation() or self.tab1 in checkBox(), those attributes don't exist on the class instance, hence the AttributeError.
The Fix
To make these variables accessible across all methods of your class, you need to prefix them with self. when initializing them. This binds them to the class instance, making them available via self in other methods.
Corrected Code
import tkinter as tk from tkinter import * from tkinter import ttk root = Tk() class UICreation(): def __init__(self): print("I m in __init__") # Use self. to make these instance attributes self.tabControl = ttk.Notebook(root) self.tab1 = ttk.Frame(self.tabControl) self.tab2 = ttk.Frame(self.tabControl) def tabCreation(self): print("I M in Tab Creation") self.tabControl.add(self.tab1, text="select ") self.tabControl.add(self.tab2, text="Add ") self.tabControl.grid() def checkBox(self): print("I M in checkBox") # Also, consider using self. for CheckBox1 if you need to access it later CheckBox1 = Checkbutton(self.tab1, text="Check1") CheckBox1.grid() if __name__ == '__main__': ui = UICreation() ui.tabCreation() ui.checkBox() root.mainloop()
Additional Note
If you ever need to modify or reference CheckBox1 in another method later on, you should also initialize it with self.CheckBox1—similar to how we fixed tabControl, tab1, and tab2. For now, since you're just placing it and don't need to interact with it elsewhere, the local variable is fine.
内容的提问来源于stack exchange,提问作者user2910787

