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.
Related
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)
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 ?
I am watching Sentdex's Tkinter tutorial and there are some related problems that arise:
Basic Class Questions that I'm just new to: How come Frame follows after the declaration of the Window class (sorry for a basic class question)? How is self.pack working without specifying what to pack?
What does frame.__init__ contribute to this code?
The code is this:
from tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, bg='LightBlue')
self.master = master
self.init_window()
def init_window(self):
self.master.title("GUI")
self.master.geometry('400x400')
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text='Quit')
quitButton.place(x=0, y=0)
root = Tk()
app = Window(root)
root.mainloop()
Thanks in advance!
The class Window inherits from tk.Frame, this is what (Frame) after Window means.
In such a situation, Window is also a tk.Frame, hence when calling pack() on self, it is in essence packing itself.
It is likely less confusing to avoid star imports:
import tkinter as tk
class Window(tk.Frame): # <-- avoid star imports
def __init__(self, master=None):
self.master = master
super().__init__(master, bg='LightBlue') # <-- use super instead of hardcoding the parent class
self.init_window()
def init_window(self):
self.master.title("GUI")
self.master.geometry('400x400')
self.pack(fill=tk.BOTH, expand=True)
self.quit_button = tk.Button(self, text='Quit',
command=self.master.destroy)
self.quit_button.pack()
if __name__ == '__main__':
root = tk.Tk()
app = Window(root)
root.mainloop()
Frame is in brackets so that the class Window can inherit the methods of the tkinter.Frame class.
The Frame.init function initialises the class as a tkinter Frame.
The self.pack() line packs the Frame into self.master, which was created a couple of lines before.
Have a look at some basic classes and build up from there.
I did this tutorial a little while ago and found that I had to spend a little time having a look at classes first. I used some youtube videos I think, good luck!
I wrote a script in a .py file that I would like to call from another main file of my program. But when I do that, it does not initialize and give the same output as when runned directly.
here's the code of the main file where I import the subTest file as a module and call it when the user clicks on a button:
#!/usr/bin/python
import tkinter as tk
from tkinter import ttk
import subTest
from subTest import SubTest
class Window(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
tk.Tk.wm_title(self, "Test")
self.parent = parent
self.initialize()
def initialize(self):
self.geometry("600x300+30+30")
label = tk.Label(self, text="Test")
label.pack(pady=20,padx=10)
self.button = ttk.Button(self, text='gotosubtest', command = self.callsubtest)
self.button.pack()
def callsubtest(self):
app = SubTest(None)
app.mainloop()
if __name__ == "__main__":
window = Window(None)
window.mainloop()
and here's the code of the subTest file containing an Entry text box which should be initialized at 320. This is a simplified example of the problem. when subTest is executed directly, this Entry default value is shown in the text box. But when subTest is called from the main, the value is not shown.
Any idea what's wrong with my code? thanks in advance to all useful tips for a python beginner ;)
#!/usr/bin/python
import tkinter as tk
from tkinter import Entry
class SubTest(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
tk.Tk.wm_title(self, "SubTest")
self.parent = parent
self.initializesubtest()
def initializesubtest(self):
self.geometry("510x480")
self.minx = tk.DoubleVar()
self.minx.set(320)
Entry(self, textvariable=self.minx,width=5).grid(row=21,column=1)
tk.Label(self, text="Min X").grid(row=22,column=1)
if __name__ == "__main__":
app = SubTest(None)
app.mainloop()
You can only have a single instance of Tk in a program. When you use that other module you are creating a second root window. For you to be able to use that second module in the first, it cannot create its own root window.
I have a tkinter menu that lets the user choose some functions. I would like if the output of that functions was presented on a texbox in Tkinter instead of the Shell. Im very unexperienced with Tkinter. I donĀ“t have any ideia how to do it..
Some of the functions require inputs of the user, is it possible for the user to input directly from Tkinter Gui?
The code for the menu of the program:
the functions: situacaocorrente(), findfuncionario(), verhistorico() are not presented here.
CODE
from Tkinter import Tk, Frame, Menu, Label, Text
import sys
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.output = Text(self)
self.output.pack()
sys.stdout = self
self.initUI()
def initUI(self):
self.parent.title("High Flex")
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Procurar funcionario", command=self.procurarfuncionario)
fileMenu.add_command(label="Ver Historico", command=self.historico)
fileMenu.add_command(label="Verificar Onde se encontram os funcionarios", command=self.funcionariosturno)
fileMenu.add_command(label="Sair", command=self.onExit)
menubar.add_cascade(label="INICIAR", menu=fileMenu)
def funcionariosturno(self):
situacaocorrente()
def procurarfuncionario(self):
findfuncionario()
def historico (self):
verhistorico()
def onExit(self):
self.quit()
def write(self, txt):
self.output.insert(END,str(txt))
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
You can use Entry() to get user input. See more on: An Introduction to Tkinter
I don't know what functions output you try to put in self.output - from external program in shell or from python function.
sys.stdout = self works only with Python functions like print