Могу ли я определить функцию для создания виджетов Tkinter внутри класса? - PullRequest
0 голосов
/ 10 апреля 2019

Я создал класс для определения окон Tkinter и его виджетов.Каждая кнопка принимает несколько параметров в качестве параметров.Вместо того, чтобы копировать и вставлять две строки, создавая и позиционируя кнопку, я хочу определить функцию внутри класса.После этого я передаю значения параметров в качестве параметров при вызове и быстро создаю новые кнопки.

from tkinter import *

class Window:
    def __init__(self, master):
        self.master = master
        master.title("UDP")

        self.label = Label(master, text="Window1")
        self.label.place(relx=0.9, rely=0.9)

        self.canvas = Canvas(master,
                             bg="red",
                             width=1160,
                             height=772
                             )
        self.canvas.grid()

        self.image = PhotoImage(file="E:\\Python\\world_map.png")
        self.canvas.create_image(0, 0, anchor=NW, image=self.image)

        self.one = Button(master, 
                          text="1", 
                          command=self.one, 
                          bg="red", bd=8, 
                          height=2, 
                          width=10, 
                          activebackground="blue")
        self.one.place(relx=0.6, 
                       rely=0.9)

        self.two = Button(master, 
                          text="2", 
                          command=self.two, 
                          bg="red",
                          bd=8, 
                          height=2, 
                          width=10, 
                          activebackground="blue")
        self.two.place(relx=0.7, 
                       rely=0.9)


        self.three = Button(master, 
                            text="3", 
                            command=self.three, 
                            bg="red", 
                            bd=8, 
                            height=2, 
                            width=10, 
                            activebackground="blue")
        self.three.place(relx=0.8, 
                         rely=0.9)

        self.close_button = Button(master, 
                                   text="Quit", 
                                   command=master.quit, 
                                   bg='red', 
                                   bd=8, 
                                   height=2, 
                                   width=10, 
                                   activebackground="blue")
        self.close_button.place(relx=0.9, 
                                rely=0.9)

class button(Window):
    def __init__(self):
        super(Window, self).__init__()
    def button_gen(self, x, y, z, a, b, c, d, e):
        self.one = Button(self, text=x,
                    command=self.one,
                    bg=y,
                    bd=z,
                    height=a,
                    width=b,
                    activebackground=c)
        self.one.place(relx=d,
                       rely=e)

    button_gen(
               "4",
               "red",
               8,
               2,
               10,
               "blue",
               0.1,
               0.2
                )

    def one(self):
        print("1")
    def two(self):
        print("2")
    def three(self):
        print("3")



root = Tk()
lbl = Label(root, text="5")
my_gui = Window(root)
root.mainloop()

Однако я получаю следующую ошибку:

Traceback (most recent call last):
  File "E:/Python/Tkinter.py", line 34, in <module>
    class button(Window):
  File "E:/Python/Tkinter.py", line 56, in button
    0.2
TypeError: button_gen() missing 1 required positional argument: 'e'

1 Ответ

1 голос
/ 10 апреля 2019

Вопрос : Наследовать от tkinter виджета

Используйте свой собственный объект виджета, который унаследован от виджета tkinter.Button.


Вместо повторения общих параметров, таких как:

    self.one = Button(master, 
                      text="1", 
                      command=self.one, 
                      bg="red", bd=8, 
                      height=2, 
                      width=10, 
                      activebackground="blue")
    self.one.place(relx=0.6, 
                   rely=0.9)

Определите свой собственный class MyButton, который определяет все общий параметр для всех Button внутри класса.

class MyButton(tk.Button): 
    def __init__(self, parent, relx, rely, **kwargs): 
        super().__init__(parent, kwargs,
                         bg="red", bd=8, height=2, width=10, activebackground="blue")

        self.place(relx=relx, rely=rely)

Использование

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.one = MyButton(self, 0.6, 0.9, text="1", command=self.one)
        self.two = MyButton(self, 0.7, 0.9, text="2", command=self.two)
        self.three = MyButton(self, 0.8, 0.9, text="3", command=self.three)

        # Alternative
        relx = 0.6
        for cfg in [("1", self.one), ("2", self.two), ("3", self.three)]:
            MyButton(self, relx, 0.9, text=cfg[0], command=cfg[1])
            relx += 0.1

if __name__ == "__main__":
    App().mainloop()

Проверено на Python: 3,5

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...