Student
Student

Reputation: 195

Python GUI - Linking one GUI in a class to another class

What I am trying to do is to link a GUI from one class in a separate file to another. My first class is a main menu which will display a few buttons that will link to another window. The second class displays a different window, but the problem I am having at the moment is that I don't know how to link the button in the first class to call the second class. Here's the code I have so far:

First file, the main menu:

from tkinter import *
import prac2_link


class main:
    def __init__(self,master):
        frame = Frame(master, width=80, height=50)
        frame.pack()
        self.hello = Label(frame, text="MAIN MENU").grid()
        self.cont = Button(frame,text="Menu option 1", command=prac2_link.main2).grid(row=1)



root = Tk()
application = main(root)
root.mainloop()

second file:

from tkinter import *

class main2:
    def __init__(self):
        frame1 = Frame(self, width=80, height=50)
        frame1.pack()
        self.hello = Label(frame1, text="hello, its another frame").grid(row=0,column=0)

Upvotes: 1

Views: 2135

Answers (1)

A. Rodas
A. Rodas

Reputation: 20679

To create a new window, you have to use a Toplevel widget. You can use it as a superclass for your main2 class:

class main2(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)
        self.frame= Frame(self, width=80, height=50)
        self.label = Label(self.frame, text='this is another frame')
        self.frame.grid()
        self.label.grid()

Then you only have to create an instance in the event handler of the Button in the other class:

class main1:
    def __init__(self, master):
        # ...
        self.cont = Button(frame,text="Menu option 1", command=self.open_main2).grid(row=1)
    def open_main2(self):
        prac2_link.main2()

Upvotes: 1

Related Questions