I'm trying to write a simple tkinter application with two frames and a controller. However when I try to implement the Notebook widget in the controller, it seems to do nothing.
import tkinter as tk
from tkinter import ttk
class WrapFrame(tk.Frame):
def __init__(self, root):
super().__init__(root)
class UnwrapFrame(tk.Frame):
def __init__(self, root):
super().__init__(root)
class Controller(tk.Frame):
def __init__(self, root):
super().__init__(root)
# Notebook
notebook = ttk.Notebook(self)
wrap_frame = WrapFrame(notebook)
unwrap_frame = UnwrapFrame(notebook)
notebook.add(wrap_frame, text="Wrap")
notebook.add(unwrap_frame, text="Unwrap")
notebook.pack()
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('Mod')
self.geometry('300x200')
self.resizable(False, False)
app = App()
Controller(app)
app.mainloop()
Output:
Controller is a frame. You never call pack, place, or grid on the instance of Controller. Since it's not visible, everything in it won't be visible either.
You need to do something like this:
controller = Controller(app)
controller.pack(fill="both", expand=True)
Related
why do i get this error?
this is my first time trying to understand what is going in a class but i cant seem to figure it out.
the app variable saves it as tkinter windowframe and that way i can put widgets on it but if i need to change the geometry how would i do this?. im sorry for my bad explaining.
Any help would do.
import tkinter as tk
class App(tk.Frame):
def __init__(self, parent):
app = tk.Frame.__init__(self, parent)
self.button = tk.Button(app, text="start")
self.button.pack()
app.geometry("500x400")
if __name__ == "__main__":
app1 = tk.Tk()
App(app1)
app1.mainloop()
When you pass a parameter to class constructor, simply assign it to an instance property (by typing self.instanceProperty = whatYouPassed), then you can work on it.
import tkinter as tk
class App:
def __init__(self, parent):
self.app = parent
self.app.geometry("500x400")
self.button = tk.Button(self.app, text="start")
self.button.pack()
if __name__ == "__main__":
app1 = tk.Tk()
App(app1)
app1.mainloop()
Reading doc about classes might be useful.
There are some similar questions already on this site. The difference is that I'm coding the Tkinter window as a class. Then making an instance in another file. For example:
import file
gui = file.Window()
gui.mainloop()
# The program continues, using the variables chosen by the user in the previous window.
while file is another file that contains the window code:
import tkinter as tk
class Window(tk.Tk):
def __init__(self, master):
# some code
def mainWidgets(self):
self.body = Body(self)
self.body.grid(row=0, column=0)
class Body(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.widgets()
def widgets(self):
# Labels entries and selections
self.boton_enviar = tk.Button(self, text='Send', command=self.send)
self.boton_enviar.grid()
def send(self):
variables = self.variables
# What code do I add here?
self.quit()
So I want to close the window when clicking the 'Send' button but I need to retrieve some variables to use in the main program. How can I do this ?
In my program, I am creating a window from my root tkinter window, and hiding the root using the .withdraw() function. When I try to show the root window again by calling the root class, it does not show and my program exits. Here's a rough outline of my code describing the problem:
class MainGUI:
def __init__(self, master):
self.master = master
#....Create and .grid() all GUI Widgets....
# Button for switching to other window
button = Button(text="CLICKME", command=lambda: self.other_window())
# Call and define show function at the end of __init__
self.show()
def show(self):
self.master.update()
self.master.deiconify()
# Create other window and withdraw self on button click
def other_window(self):
OtherGUI(self.master)
self.master.withdraw()
class OtherGUI:
def __init__(self, master):
# Function for returning to main window, calls MainGUI class
# to create window and withdraws self.
def main_window():
MainGUI(self.master)
self.master.withdraw()
master = self.master = Toplevel(master)
#....Create and .grid() all GUI Widgets....
# Button for switching back to main window
button = Button(text="CLICKME", command=lambda: self.main_window())
Using print functions in the MainGUI, I was able to see that when trying to switch back to the main window, show() is actually called, and the entire class does appear to be entered.
This puzzles me as I've only really learn how to do this from other forum posts, and using root.update() and .deiconify() seemed to be the solution for most people, however I have no idea why this isn't working.
Does anyone have an idea as to where I'm going wrong here?
The example you presented will not work for several reason.
#really you should build your gui as an inherited class as it makes things much easier to manage in tkinter.
class MainGUI:
def __init__(self, master):
self.master = master
button = Button(text="CLICKME", command=lambda: self.other_window())
# no need for lambda expressions here.
# missing geometry layout... grid(), pack() or place()
self.show()
# self.show does nothing here because your show method is improperly indented.
# your other_window method is also not properly indented.
def show(self):
self.master.update()
self.master.deiconify()
def other_window(self):
OtherGUI(self.master)
self.master.withdraw()
class OtherGUI:
def __init__(self, master):
# this function should be its own method.
def main_window():
MainGUI(self.master)
self.master.withdraw()
master = self.master = Toplevel(master)
# this is not how you should be defining master.
button = Button(text="CLICKME", command=lambda: self.main_window())
# missing geometry layout... grid(), pack() or place()
# your button command is using a lambda to call a class method but your define it as a function instead.
Here is a simpler version of what you are attempting that will work:
import tkinter as tk
class MainGUI(tk.Tk):
def __init__(self):
super().__init__()
tk.Button(self, text="Open Toplevel", command=self.open_toplevel_window).pack()
def open_toplevel_window(self):
OtherGUI(self)
self.withdraw()
class OtherGUI(tk.Toplevel):
def __init__(self, master):
super().__init__()
tk.Button(self, text="Close top and deiconify main", command=self.main_window).pack()
def main_window(self):
self.master.deiconify()
self.destroy()
MainGUI().mainloop()
As you can see here when you inherit from the tkinter classes that control the main window and toplevel windows it becomes easier to manage them and less code to perform a task.
I have the following problem. I created a gui with Tkinter and when I run it in my IDE (Spyder) everything works perfectly fine, but when I save the file as and want to start it by just executing the .py, everytime a window is created or a dialog opens, a second Tkinter window is poping up. Same problem appears when I save the code as .pyw .
I posted a short example that lasts in the same Problem.
import tkinter as tk
from tkinter import messagebox
class test_GUI(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self._initializeWindow()
self._window.protocol("WM_DELETE_WINDOW", self.__on_closing)
self._window.mainloop()
def _initializeWindow(self):
self._window=tk.Tk()
self._window.title("The window I initzialized")
def __on_closing(self):
if(messagebox.askokcancel("Quit", "Quit program?")):
self._window.destroy()
self._window.quit()
app=test_GUI()
You define your class as
class test_GUI(tk.Frame):
so your class inherits from tk.Frame, which means that your class basically is a Frame with extra features.
When you do
super().__init__(master)
You initialize the class from which you are inheriting, which is tk.Frame. At this time, there is no tk.Tk object (and master=None). Because a Frame (or any other tkinter widget) cannot exist without an instance of tk.Tk, tkinter silently makes one for you. This is your first window.
After that you call
self._window = tk.Tk()
to make a tk.Tk instance yourself. This is your second window. Besides that you don't want two windows, you should never have more than one instance of tk.Tk (or more accurately the associated Tcl interpreter) running at the same time because this leads to unexpected behavior.
So how can you fix this?
You basically have two options: remove inheritance or initiate tk.Tk before initiating your class.
Without inheritance your app can be structured like
import tkinter as tk
class test_GUI():
def __init__(self):
self._window=tk.Tk()
self._window.title("The window I initzialized")
self.button = tk.Button(self._window, text='Test button')
self.button.pack()
...
self._window.mainloop()
With inheritance you can do it like this
import tkinter as tk
class test_GUI(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("The window I initzialized")
self.button = tk.Button(self, text='Test button')
self.button.pack()
root = tk.Tk()
app=test_GUI(root)
app.pack(fill='both', expand=True)
root.mainloop()
Both ways work fine. I personally like the version with inheritance. Also check out Bryan Oakley's post on structuring a tkinter application here.
def _initializeWindow(self):
self._window=tk.Tk()
self._window.title("The window I initzialized")
self._window.withdraw()
self._window.withdraw() will remove the second window.
super().__init__(master) is actually responsible for the first window. Comment it out. In that case you won't need to withdraw the window you created in _initializeWindow.
import tkinter as tk
from tkinter import messagebox
class test_GUI(tk.Frame):
def __init__(self,master=None):
#super().__init__(master)
self._initializeWindow()
self._window.protocol("WM_DELETE_WINDOW", self.__on_closing)
self._window.mainloop()
def _initializeWindow(self):
self._window=tk.Tk()
self._window.title("The window I initzialized")
#self._window.withdraw()
def __on_closing(self):
if(messagebox.askokcancel("Quit", "Quit program?")):
self._window.destroy()
self._window.quit()
app=test_GUI()
For those attempting to unit test your GUI and trying to insert the root tk dependency via dataclasses, you can fix the multi window problem by putting tk initialization in the __post_init__ method:
from dataclasses import dataclass
import tkinter as tk
#dataclass
class App():
tk_root: tk.Tk = None
def __post_init__(self):
if self.tk_root is None:
self.tk_root = tk.Tk()
# ...
Then, if you utilize tkinter classes (like StringVars) that need a root Tk to be initialized, you'll need to patch tk in your pytest fixture:
import pytest
from unittest.mock import patch, MagicMock
from GUI import App
#pytest.fixture
def app():
with patch('GUI.tk'):
return GUI(tk_root=MagicMock())
I'm a python beginner making a program that is supposed to save and present reservations for a campingsite (just for fun...). I've structured it in an OOP-way meaning that I define a class for each seperate window. What I need to do is to update a TopLevel window (SubWindow2) presenting database entries, when another TopLevel window (created from Subwindow2) is closed.
import Tkinter as tk
class MenuWindow(tk.Tk):
def __init__(self, master):
self.master = master
#Widgets
def open_subwindow1(self):
self.window = Toplevel(self.master)
self.SubSubWindow1 = SubSubWindow1(self.window)
def open_subwindow2(self):
self.window = Toplevel(self.master)
self.SubSubWindow2 = SubSubWindow2(self.window)
class SubWindow1(tk.Tk):
def __init__(self, master):
self.master = master
#Widgets
class Subwindow2(tk.TopLevel):
def __init__(self, master):
self.master = master
#Widgets
self.button = tk.Button(master, text='Quit', command=open_subsub1)
def load_values(self):
#loading sqlite db-values into listboxes
def open_subsub1(self):
self.window = Toplevel(self.master)
self.SubSubWindow1 = SubSubWindow1(self.window)
class SubSubWindow1(tk.TopLevel):
def __init__(self, master):
self.master = master
#Widgets
self.button = tk.Button(master, text='Quit', command=on_quit)
def on_quit(self):
#Here I want to call a function that updates SubWindow2 (loads sqlite database values into several listboxes)
self.master.destroy()
root = tk.Tk()
myprog = MyProg(root)
root.mainloop()
How can i access a function in Subwindow2 from SubSubWindow1? self.master only refers to the TopLevel() instance right?
def on_quit(self):
self.SubWindow2.load_values()
self.master.destroy()
doesn't work, I get a TypeError: unbound method load_values() must be called with SubWindow2 instance as first argument (got nothing instead)
Is this an unvalid approch to "nesting" TopLevel-windows? What's the alternative?
Any remarks are greatly appriciated! Thanks for any help
I should preface this by claiming that I am also a novice, and I would greatly appreciate the advice of others in order not to spread misinformation.
From what I can see, you have some misunderstandings with how inheritance vs. encapsulation works in Python. Firstly, within a Tkinter application, there should only be a single instance of Tk(). Within your class definitions, you declare...
class SubWindow1(tk.Tk):
This means that whenever you create a new SubWindow1, a new instance of Tk will become instantiated with it, and SubWindow1 will inherit all of its properties.
If you would like to create a class that refers to, and has all the properties, of a Toplevel instance, your Subwindow2 was correct.
class Subwindow2(tk.TopLevel):
However, within the init, you must also initialize this instance of Toplevel as so:
class SubWindow2(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self)
self.master = master
Each 'master' refers to the element above it. Tk applications work as a tree hierarchy. This is why you should only have one instance of Tk(), which works as your 'root.' This instance of Tk contains windows within it, which contains windows or elements within them. So each window or element will have a parent, referred to as master, so you will be able to navigate around.
So when you create an instance of SubWindow2, this refers to everything within your SubWindow2, along with everything included in an instance of Toplevel. Because 'self' now refers to a Toplevel, you can pass it into the children to be a master, as such:
self.sub_sub_window1 = SubSubWindow1(self)
self.master only refers to the TopLevel() instance right?
Yes, but since you will be inheriting all of the Toplevel attributes through your SubWindow2 inheritance, you can add on more methods and still refer to them through your self.master tag.
Lastly, you should also call pack() on elements that you would like to show up correctly on your windows.
Altogether, I've made some edits to your program to try and demonstrate some of the concepts of inheritance and how it works within a Tkinter application. I hope you can look at this and take something from it. Please let me know if there are any elements you disagree with, as it is nowhere near perfect.
import Tkinter as tk
class MenuWindow():
def __init__(self, master):
self.master = master
self.sub_window_1 = SubWindow1(self.master)
self.sub_window_2 = SubWindow2(self.master)
class SubWindow1(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self)
self.master = master
class SubWindow2(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self)
self.master = master
self.sub_sub_window1 = SubSubWindow1(self)
def print_hello(self):
print "Hello!"
class SubSubWindow1(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self)
self.master = master
self.button = tk.Button(self.master, text='Say Hello & Destroy', command=self.on_quit)
self.button.pack()
def on_quit(self):
self.master.print_hello()
self.master.destroy()
root = tk.Tk()
myprog = MenuWindow(root)
root.mainloop()