doomslug
doomslug

Reputation: 113

Create a tkinter button in separate class

I am making my first real Tkinter application in Python 3.4. I have made a few simpler things with Tkinter, but nothing as advanced as this one.

Part of my program is to have a window that has two buttons, one on each side, and a picture in the middle. The buttons will navigate through pictures to the left and right.

I want my buttons to be able to be created through a separate class NavButton so my code is more organized and easier to read like in this picture from the question Best way to structure a tkinter application.

enter image description here

Essentially I want to say:

self.left_button = NavButton(self, ">")

or something similar to create a

class NavButton():

object.

Then pack it with

self.left_button.pack()

I am struggling with how to actually make a button be set up in a different class. It keeps saying 'AttributeError: 'NavButton' object has no attribute 'tk' '

Here is my code so far:

import tkinter as tk

class MainWindow(tk.Frame):
    def __init__(self, master):
        frame = tk.Frame(master)
        frame.pack(fill="both", expand = True)

        self.left_button = NavButton(frame, ">")
        self.left_button.pack(side='left', fill='y')

class NavButton(tk.Frame):
    def __init__(self, master, icon):
        self.nav_button = tk.Button(master, text=icon, width=25)


root = tk.Tk()
root.title("Viewer")
root.geometry('1000x600')
app = MainWindow(root)
root.mainloop()

Could my problem come from the way I create the buttons?

tk.Frame.__init__(self, parent, ...)

VS

self.frame = tk.Frame(parent)

So in a nutshell, how do I use a separate class for my button?

Upvotes: 1

Views: 6928

Answers (1)

Zizouz212
Zizouz212

Reputation: 4998

Your NavButton is a frame. I would make it a button, that's what you want, isn't it? Change this:

class NavButton(Tk.Frame):

to

class NavButton(Tk.Button):

Also, you should call the parent initializer:

super().__init__(self, **options)

Upvotes: 3

Related Questions