如何配置不同类的窗口小部件?

时间:2018-09-09 17:57:50

标签: python-3.x tkinter object-oriented-database

我需要LeftFrame中的按钮才能在单击时更改其外观。在类AccOne中,我尝试做left_frame.acc1.config(releif='SUNKEN'),但得到NameError:未定义名称'left_frame'。我尝试将left_frame设置为全局,但是没有运气。

这是脚本。

class MainApp(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)



        container = Frame(self)
        container.pack()

        container.rowconfigure(4, weight=1)
        container.columnconfigure(2, weight=1)

        right_frame = RightFrame(container, self)
        left_frame = LeftFrame(container, right_frame)

        left_frame.pack(side=LEFT)
        right_frame.pack()

class RightFrame(Frame):
    def __init__(self, parent, controller, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)

        self.frames = {}
        for F in (Welcome, AccOne, AccTwo, AccThree, AccFour, AccFive):
            frame = F(self, self)
            self.frames[F] = frame

        self.show_frame(Welcome)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.grid(row=0, column=0)
        frame.tkraise()

class LeftFrame(Frame):
    def __init__(self, parent, controller, *args, **kwargs):
        Frame.__init__(self, parent)

        acc1 = Button(self, text="Account 1", width=12, height=3, command=lambda: controller.show_frame(AccOne))
        acc1.pack()

我认为在def show_frame(self,cont):下配置按钮是合理的,但是由于该方法不在LeftFrame下,因此我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

在创建带有类的tkinter窗口时,请尝试考虑创建“小部件树”,这是您可以访问所有小部件的路径。在这个简单的示例中,MainWindow和SubWindow可以访问彼此的所有小部件:

class MainWindow(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        # widget
        self.lbl = tk.Label(self, text='Title')
        self.lbl.pack()

        # create child window, as class attribute so it can access all
        # of the child's widgets
        self.child = SubWindow(self)
        self.child.pack()

        # access child's widgets
        self.child.btn.config(bg='red')


class SubWindow(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        # can use this attribute to move 'up the tree' and access
        # all of mainwindow's widgets
        self.parent = parent

        # widget
        self.btn = tk.Button(self, text='Press')
        self.btn.pack()

        # access parent's widgets
        self.parent.lbl.config(text='Changed')

要更改代码的内容

首先,每次创建以后可能要访问的窗口小部件时,请将其分配给类变量。例如(这是造成问题的一部分):

self.left_frame
self.acc1

不是

left_frame
acc1

第二,正确使用您的父参数和控制器参数。您正在执行这些操作,但是您永远不会使用它们或将它们分配给一个属性,因此它们可能不存在。将它们分配给self.parentself.controller属性,因此,如果以后需要使用方法访问它们,则可以。

我不确定您要做什么,也看不到您的AccOne类,但是您应该能够通过进行这些更改来找到访问该按钮的方法。

祝你好运!