Tkinter中如何在x.py获取page2.py的checkbox控件实现联动
解决方案
核心问题是Page2类中的复选框是局部变量,外部无法访问,同时main.py和x.py都没有正确获取到Page2实例的控件引用。按照你的结构需求,可通过以下步骤解决:
步骤1:将Page2中的复选框改为实例属性
修改page2.py,把局部的checkbox1、checkbox2改为类的实例属性,同时初始化对应的IntVar变量:
import tkinter as tk class Page2(tk.Frame): def __init__(self, master, **kw): super().__init__(master, **kw) # 初始化复选框对应的变量 self.checkbox1_var = tk.IntVar() self.checkbox2_var = tk.IntVar() # CHECKBOX 1 def test_checkbox1(): print("Printed Checkbox 1") self.checkbox1 = tk.Checkbutton(self, text="Checkbox 1", variable=self.checkbox1_var, onvalue=1, offvalue=0, height=1, highlightthickness=0, command=test_checkbox1) self.checkbox1.place(x=250, y=30) # CHECKBOX 2 def test_checkbox2(): print("Printed Checkbox 2") self.checkbox2 = tk.Checkbutton(self, text="Checkbox 2", variable=self.checkbox2_var, onvalue=1, offvalue=0, height=1, highlightthickness=0, command=test_checkbox2) self.checkbox2.place(x=250, y=60)
步骤2:在main.py中传递Page2实例给myfunction
修改main.py的on_tab_selection_changed函数,调用myfunction时把page2实例作为参数传入:
import tkinter as tk from tkinter import Frame, Label, ttk from page1 import Page1 from page2 import Page2 from x import * root = tk.Tk() root.geometry('475x325') style = ttk.Style() style.theme_use('default') nb = ttk.Notebook(root) nb.pack(fill='both', expand=1) page1 = Page1(nb) page2 = Page2(nb) nb.add(page1, text='Tab1', compound='left') nb.add(page2, text='Tab2', compound='left') Verticalbar = Frame(root, width=200, height=300, background="white", highlightthickness=0) Verticalbar.place(x=1, y=40) def on_tab_selection_changed(event): tab_id = nb.select() tab_text = nb.tab(tab_id, "text") if tab_text == "Tab1": newlabel1 = Label(Verticalbar, text='TAB 1 EXAMPLE ', background="white", fg="#78b130", font='Arial 10 bold') newlabel1.place(x=2, y=3) if tab_text == "Tab2": # 传递page2实例给myfunction myfunction(Verticalbar, page2) nb.bind("<<NotebookTabChanged>>", on_tab_selection_changed) root.mainloop()
步骤3:修改x.py接收Page2实例并访问复选框
修改x.py的myfunction,接收page2参数,然后在select_first_and_second中通过实例访问复选框,同时修复未定义的ckbx_intvar变量:
from tkinter import Label import tkinter as tk def myfunction(Verticalbar, page2): newlabel2 = Label(Verticalbar, text='TAB 2 EXAMPLE', background="white", fg="#78b130", font='Arial 10 bold') newlabel2.place(x=2, y=3) # 初始化全选复选框的变量 ckbx_intvar = tk.IntVar() def select_first_and_second(): # 通过page2实例获取两个复选框 all_checkbox = [page2.checkbox1, page2.checkbox2] for cb in all_checkbox: cb.invoke() ### CHECKBOX SELECT ALL ### ckbx = tk.Checkbutton(Verticalbar, text="Select all", variable=ckbx_intvar, onvalue=1, offvalue=0, height=1, highlightthickness=0, command=select_first_and_second) ckbx.place(x=0, y=30)
关键说明
- Page2中的复选框改为实例属性后,外部可通过
page2.checkbox1、page2.checkbox2直接访问控件 - main.py持有Page2的实例,将其传递给x.py的myfunction,让x.py能拿到需要操作的复选框引用
- 修复了x.py中未定义的
ckbx_intvar变量,避免另一个潜在报错
内容的提问来源于stack exchange,提问作者Nodigap
相关产品推荐
相关产品推荐

