创建用于不同框架的 Tkinter 按钮列表或字典

Create a list or dictionary of Tkinter buttons to use in different frames

所以我的 Tkinter 应用程序包含多个框架

所有这些多个框架都包含许多按钮的相同基本结构;唯一的区别是每个页面上的按钮有不同的 bg

在我的实际项目中,这些按钮包含很多选项,因此每次都必须为所有页面编写相同的基本代码,这让我的代码看起来很长。

所以我在想:有没有办法将所有这些按钮放入字典或列表中,并将它们打包到每个单独的框架中? (请记住,按钮需要从特定框架继承 bg 变量。)

我创建了一个最小示例来说明我的意思:

import tkinter as tk 
from tkinter import *

listt = []
self = None
bg_colour_for_this_frame = None
button1 = Button(self,text="Button 1",bg=bg_colour_for_this_frame,fg='white')
button2 = Button(self,text="Button 2",bg=bg_colour_for_this_frame,fg='blue')
button3 = Button(self,text="Button 3",bg=bg_colour_for_this_frame,fg='orange')
listt.append(button1)
listt.append(button2)
listt.append(button3)

class Tkinter(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for F in (StartPage, SecondPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.winfo_toplevel().geometry("860x864")
        frame.configure(bg='#000000')

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        Button(self,text='SecondPage',command=lambda:controller.show_frame(SecondPage)).pack()
        for s in listt:
            s.pack()

class SecondPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        Button(self,text='StartPage',command=lambda:controller.show_frame(StartPage)).pack()
        for s in listt:
            s.pack()

app = Tkinter()
app.mainloop()

或者,也许不用列表,而是使用字典:

listt = {'button1':'Button[root,text="Button 1",bg=bg_colour_for_this_frame,fg="white"]',
        'button2':'Button[root,text="Button 2",bg=bg_colour_for_this_frame,fg="red"]',
        'button3':'Button[root,text="Button 3",bg=bg_colour_for_this_frame,fg="blue"]',
       }

我收到错误:

s.pack()
AttributeError: 'str' object has no attribute 'pack'

因为你不能在它们所在的页面存在之前创建 Buttons,所以创建一个函数并在每个页面的初始化期间调用它会更简单 classes — 如下所示 make_buttons()

import tkinter as tk
from tkinter import *

# Button options for all pages.
BTN_OPTS = [dict(text="Button 1", fg='white'),
            dict(text="Button 2", fg='blue'),
            dict(text="Button 3", fg='orange')]


def make_buttons(parent, bg_colour):
    return [Button(parent, bg=bg_colour, **opts) for opts in BTN_OPTS]


class Tkinter(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, SecondPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.winfo_toplevel().geometry("860x864")
        frame.configure(bg='#000000')


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        Button(self, text='SecondPage',
               command=lambda: controller.show_frame(SecondPage)).pack()
        for btn in make_buttons(self, 'Pink'):
            btn.pack()


class SecondPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        Button(self, text='StartPage',
               command=lambda: controller.show_frame(StartPage)).pack()
        for btn in make_buttons(self, 'green'):
            btn.pack()

app = Tkinter()
app.mainloop()

一种更复杂且 object-oriented 的方法是为所有页面 class 定义一个基础 class,其中包含类似于上述函数的方法,然后派生具体的 subclasses 允许他们继承方法。它还摆脱了全局数据,因为按钮选项现在位于(基本)class 属性中。

这是一个可运行的示例,说明如何以这种方式完成。 注意: 它需要 Python 3.6+,因为它使用了 object.__init_subclass__() 并在该版本中添加:

import tkinter as tk


class Tkinter(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, SecondPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.winfo_toplevel().geometry("860x864")
        frame.configure(bg='#000000')


class BasePage(tk.Frame):
    # Button options common to all pages.
    BTN_OPTS = [dict(text="Button 1", fg='white'),
                dict(text="Button 2", fg='blue'),
                dict(text="Button 3", fg='orange')]

    @classmethod
    def __init_subclass__(cls, /, bg_color, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.bg_color = bg_color

    def __init__(self, parent, controller, text, command):
        super().__init__(parent)
        tk.Button(self, text=text, command=command).pack()  # Next page button.
        for btn in (tk.Button(self, bg=self.bg_color, **opts) for opts in self.BTN_OPTS):
            btn.pack()


class StartPage(BasePage, bg_color='pink'):
    def __init__(self, parent, controller):
        super().__init__(parent, controller, text='SecondPage',
                         command=lambda: controller.show_frame(SecondPage))


class SecondPage(BasePage, bg_color='green'):
    def __init__(self, parent, controller):
        super().__init__(parent, controller, text='StartPage',
                         command=lambda: controller.show_frame(StartPage))


app = Tkinter()
app.mainloop()