Python,从类外部访问小部件项

问题描述 投票:0回答:1

我有一个自动生成的代码,它生成一个GUI,里面有各种小部件。其中一个小部件是ScrolledListBox。代码的一部分如下所示:

class New_Toplevel_1:
    def __init__(self, top=None):
        self.Scrolledlistbox4.configure(background="white")
        self.Scrolledlistbox4.configure(font="TkFixedFont")
        self.Scrolledlistbox4.configure(highlightcolor="#d9d9d9")
        self.Scrolledlistbox4.configure(selectbackground="#c4c4c4")
        self.Scrolledlistbox4.configure(width=10)

我想从这个类之外访问Scrolledlistbox4。因此,例如,我想编写一个函数,只要我调用它就会更新ScrolledListBox。我对python比较陌生,想知道如何实现这个目标。

python tkinter listbox
1个回答
2
投票

您需要首先创建一个Scrolledlistbox4对象作为属性:

self.scrolled_listbox = Scrolledlistbox4(...)

然后你可以在最外层范围内完成所有配置,如:

a = New_Toplevel_1()

a.scrolled_listbox.configure(background='white')
...

在下面的示例中,"Outside Button"从外部更改了类“按钮”的text选项:

import tkinter as tk

class FrameWithButton(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.btn = tk.Button(root, text="Button")
        self.btn.pack()

root = tk.Tk()

an_instance = FrameWithButton(root)
an_instance.pack()

def update_button():
    global an_instance
    an_instance.btn['text'] = "Button Text Updated!"


tk.Button(root, text="Outside Button", command=update_button).pack()

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.