I have a big problem using tkinter with self here is my code
Could people please give an answer, thanks! The error I get is something like,self could not be given a variable outside a function.
from tkinter import *
root = Tk()
class start():
global self
self = root
def __init__():
self.title('__init__')
self.geometry('300x300')
__init__(self)
class window_extra():
def canvas(self):
global self
selfc = Canvas(self, bg='black').pack()
canvas(self)
self.mainloop()
Thanks!
You should not use self as a variable name as it is used to specify if something is an attribute of the instance of the class.
You do not need to use global in classes either as class attributes are used in most cases when dealing with variables that are needed through the class.
Judging by the code you have shown I think you are trying to do something like this:
from tkinter import *
class start():
def __init__(self, root):
self.master = root
self.master.title('__init__')
self.master.geometry('300x300')
Canvas(self.master, bg='black').pack()
root = Tk()
start(root)
root.mainloop()
However I believe you are struggling with the OOP method of programing and I would suggest to not use OOP to start with if this is the case.
Maybe take a few tutorials on youtube or hit up Codecadamy.
In response to your comments:
In my Opinion using init properly is a bad idea. I use it as a regular def. I doesn't matter if I use self global, unless the function/class variable is called self.
I respect the proper use of init, but I just find the whole thing with, init and self.master I just don't get any of it!
Lack of understanding a thing does not mean said thing is bad. The use of self.master is there to provide a class attribute that ties back to the root Tk() variable. This allows any method within the class to interact with the instance of Tk(). I can't speak to other programing languages but the use of self is a very important in OOP for python. It may not be 100% required to reserve self for referencing to either the instance of the object or the class attribute but it is the accepted and known use of self and really should not be changed/overwritten.
I restructured for some simplicity, but I think that you need a better understanding of objects in Python before going too much further down the GUI route. I think that you mean something like this:
from tkinter import *
# creates a subclass of Tk() called 'Application'; class names by convention
# use CamelCase; best to stick with convention on this one
class Application(tkinter.Tk):
# you don't have to create an explicit invocation of '__init__', it
# is automatically run when you instantiate your class (last line)
def __init__():
super().__init__() # initialize the super class (the 'tkinter.Tk()')
self.title('__init__') # use 'self' to refer to this object - do not declare it as global! it is only valid within the object!
self.geometry('300x300')
self.my_canvas = tkinter.Canvas(self, bg='black') # save an instance of your canvas for easy reference later
self.my_canvas.pack() # pack as a separate step (only required if you plan to use the canvas later... or ever)
self.mainloop() # begin the tkinter loop
# this 'if __name__ ...' is a good idea in most cases, allows you to import `Application` into other
# files without actually running it unless you want to from that other file
if __name__ == '__main__':
Application() # start your class
Related
How can I change an attribute on the object when the attribute is Frame? I want to change the color of the frame.
class MyFrame:
def __init__(self, bg_color)
self.window = tk.Frame(self.parent, bg=bg_color)
mainApp:
frame_obj = MyFrame("blue")
#want to change the color after the frame obj has been created
frame_obj.window.bg = "red" #this does not work
Tkinter is based on different progamming language, named tcl and thats why things seem a bit unpythonic here.
The tk.Frame object isnt a pure python object, rather its an wrapped object in a tcl interpreter and thats why you cant address the attributes you intuitivly think you can. You need to adress the attributes in a way the tcl interpreter is abel to handle and therefor methods are created like widget.configure.
To achive what you want with your current code, it would look like:
import tkinter as tk
root = tk.Tk()
class MyFrame():
def __init__(self, bg_color):
self.window = tk.Frame(width=500,height=500,bg=bg_color)
frame_obj = MyFrame('blue')
frame_obj.window.pack(fill=tk.BOTH)
frame_obj.window.configure(bg='yellow')
root.mainloop()
In addition, the proper way for an OOP approach for a frame would look like this:
class MyFrame(tk.Frame):
def __init__(self,master,**kwargs):
super().__init__(master)
self.configure(**kwargs)
frame_obj = MyFrame(root,width=500,height=500,bg='green')
frame_obj.pack(fill=tk.BOTH)
This way your class becomes a child of the tk.Frame object and you can adress it directly. The syntax self in this context refers directly to the tk.Frame object. Also it is good practice to use the format of
def __init__(self,master,**kwargs):
while its the same for the parent/tk.Frame. It has a single positional argument, named master and keywords arguments for the configuration of the Frame.
Please take a look at a tutorial for tkinter and for OOP. If you had you would know that. Please dont feel offended, but StackOverflow requiers a brief reasearch and that includes to read documentation and take tutorials.
Whilst working on a tkinter application (Tcl/Tk 8.6 and Python 3.9.2) I recently encountered an error that I was able to resolve, but I think the existence of the error highlights some gaps in my knowledge and potential weaknesses in my approach.
A reproducible example of the error is below - this code will not work and returns the error AttributeError: 'parent_class' object has no attribute 'first'.
from tkinter import *
from tkinter import ttk
class child_one(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.x = 10
def print_x(self):
print(self.x)
class child_two(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.b = ttk.Button(self, text='Button 1',
command=parent.first.print_x).grid()
class parent_class(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.grid()
self.second = child_two(self)
self.first = child_one(self)
self.first.grid()
self.second.grid()
if __name__ == '__main__':
root = Tk()
w = parent_class(root)
root.mainloop()
However the code will work if I reverse the order in which the instances of child_one and child_two are created i.e. replacing
self.second = child_two(self)
self.first = child_one(self)
with
self.first = child_one(self)
self.second = child_two(self)
in the definition of parent_class.
I'd really appreciate any explanations or link to resources to help me understand the program flow which causes this to happen - it appears to me that when I create w and get to the line self.second = child_two(self) Python is just looking at the part of the instance of parent_class which has already been created, and not the whole definition of the class.
Would this happen if this was not the first instance of parent_class to be created? Is it specific to tkinter? (I was only able to create a simple reproducible example with tkinter widgets, not with classes more generally.)
I suppose another solution would be to make print_x a (static?) method of parent_class? I also assume there's not enough detail here to definitively state if that (or alternative structures) would be preferable to facilitate interface between the components of my application, but would be interested to hear any suggestions for good practices in this space.
There's really no mystery here. If you do self.first = child_one(self) first, it defines self.first. When you then call child_two(self), it is able to access parent.first since it was previously created.
However, if you call child_two(self) first, at that point in time parent.first doesn't exist. Thus, when you do command=parent.first.print_x, parent.first doesn't exist.
it appears to me that when I create w and get to the line self.second = child_two(self) Python is just looking at the part of the instance of parent_class which has already been created
That is correct. You can't reference things that haven't been created yet.
Would this happen if this was not the first instance of parent_class to be created? Is it specific to tkinter?
I'm not quite sure what you're asking in the first part of that question. It will always happen if you try to reference any object attribute before that attribute has been created. And no, this isn't specific to tkinter. It's a fundamental aspect of the way that python works.
This is a good example of why it's generally best to create proper functions rather than using lambda. lambda is good when you need to pass arguments, but you don't need to do that in this case. Even then, a proper function is better than directly referencing some other object at the time the button is defined. An arguably better way would be to use a function so that self.parent.first doesn't need to be resolved until you actually click the button.
For example:
class child_two(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.parent = parent
self.b = ttk.Button(self, text='Button 1', command=self.print_x)
self.b.grid()
def print_x(self):
self.parent.first.print_x()
When you say "Python is just looking at the part of the instance of parent_class which has already been created, and not the whole definition of the class", you seem to be expecting python to have built a static description of your class before the program starts running.
Python does not work that way, it's a dynamic language. As Bryan just said, the first variable is created only when you assign to it for the first.
I have been trying to use classes for both of my files. I made a gui.py with:
class GuiStart:
def __init__(self, master):
self.master = master
self.master.title("DECTools 1.3")
I have another file with methods I want to execute. This file is called foo.py
class DecToolsClass:
def __init__(self):
self.gui = gui.GuiStart()
I get an error, because I don't give the it the master parameter. I can't set it to None because it doesn't have the .title method.
I execute the gui file with:
if __name__ == "gui":
root = tkinter.Tk()
my_gui = GuiStart(root)
root.mainloop()
The problem is that I need to execute a method from foo.py with my gui.py file and I need to access attributes from my gui.py file with my foo.py file. I have been trying to accomplish this and I know I can't use multiple constructors like in Java.
Is it possible what I want or do I have to rewrite my code?
Thanks in advance!
The GuiStart class starts the tkinter gui. The window with buttons and entries is created with that class. From the GuiStart class I call methods that do things like copy files to a certain location
Alright, so to sum it up, you have a class that handles user interaction, and a set of generic methods doing no user interaction, that GuiStart provides a Gui for. If I understand wrong, this answer will be much less useful.
It is indeed a good idea to split those, but for this split to be effective, you must not have direct references from one another. This means this is a definitive DON'T:
class DecToolsClass:
def __init__(self):
self.gui = gui.GuiStart()
If you actually needed the tools to access the gui, you'd inject it. But normally you would want it the other way around: Tools should be generic and not know about Gui at all. Onn the other hand, Gui knows about them. Assuming the rest of the code is correct (I don't know tkinter):
def main():
tools = DecToolsClass() # not shown, but it no longer has self.gui
root = tkinter.Tk()
my_gui = gui.GuiStart(root, tools)
root.mainloop()
if __name__ == '__main__':
main()
Which means of course GuiStart must take the toolset it will use as an argument:
class GuiStart:
def __init__(self, master, tools):
self.master = master
self.master.title("DECTools 1.3")
self.tools = tools
Now, everywhere in GuiStart, any use of tools must go through self.tools. As an added bonus, in your unittests you can pass a dummy tools object that just checks how it is called, that makes testing very easy.
i've recently come across a problem thats bugging me with the tkinter entry .get() function, I have put together an example code so you can see what i'm trying to do, I have two classes, a class for each window. In the first window(main window) I have an entry box, in the second window I am attempting to get the entry box text from the first window.
Here's the code: (Trying to get entry box info from the first class in the second class)
from Tkinter import *
class window_1(object):
def __init__(self):
self.app = Tk()
self.app.title("Window One")
def entrybox(self):
self.ent = Entry(self.app) #This is the text i'm trying to get in 2nd class
def button(self):
def ODV(self):
class window_2(object):
def __init__(self):
self.app2 = Tk()
self.app2.title("Window Two")
def labels(self):
self.label_0 = Label(self.app2, text = "Name: ")
def info(self):
self.fetch_name = self.ent.get()#Here is my problem
def gridder(self):
self.label_0.grid(row = 0, column = 0)
self.fetch_name.grid(row = 0, column = 1)
rooter = window_2()
rooter.labels()
rooter.info()
rooter.gridder()
open_data_viewer = lambda: ODV(self)
self.but = Button(self.app, text = "Save", command = open_data_viewer)
def packer(self):
self.ent.pack(anchor = W)
self.but.pack(anchor = W)
def App_Runner(self):
self.app.mainloop()
root = window_1()
root.entrybox()
root.button()
root.packer()
root.App_Runner()
Your first problem is that you're creating more than one instance of Tk. You can't do that, tkinter isn't designed to work that way. If you want multiple windows, create instances of Toplevel. A tkinter program should always have exactly one instance of Tk, exactly one call to mainloop, and there should be little to no code following the call to mainloop.
Second, there is absolutely no value in embedding the definition of a class inside a function. Move it out, it will make your code easier to understand, and easier to write and maintain.
Third, for an instance of one object to access a method on another object, the first object needs to know about the second object or needs to know about a central "controller" object. This isn't a tkinter problem, it's a normal thing to consider when writing OO code.
From a practical standpoint, you need to pass in a reference either to the entry widget, or the object that contains the entry widget, when you create the second object. For example:
class window_2(object):
def __init__(self, other):
...
self.other = other
...
def info(self):
self.fetch_name = self.other.ent.get()
...
rooter = window_2(self) # pass "self" to the new object
This produces a tight coupling between the two objects -- the second object knows about the inner workings of the first object. This is not very good design, though for very, very simple programs it's not so bad. The problem is this: if you change the layout of the first widget, perhaps renaming "self.ent" to "self.some_other_frame.ent", you have to modify the other class too.
A better solution is to define in your first class a function that gets it's own value. Of course, ent serves that purpose, but again, that is a tight coupling. better to have a helper function:
class window_1(object):
...
def get_string(self):
return self.ent.get()
class window_2(object):
def info(self):
self.fetch_name = self.other.get_string()
This still has a loose coupling, but one that is much easier to manage because the coupling isn't tied to the specific internal layout and names of the first window. You can change the widgets all you want, as long as you continue to provide a get_string method that does what the other class expects. Your first class is providing a contract to the second class: a promise that no matter how else the window may change over time, it promises to provide this interface.
I have a small program that batch handles files. These files use a map file to load certain settings. The map file has a line at the top that specifies for what directory it is for.
Currently I am able to read the line and assign it to the source path variable (sPath). I want to update the TextCtrl for the Source Directory, however it is in the MainFrame class and I load the map file in a different class.
class Process(wx.Panel):
def loadMap(self, event):
MainFrame.sPath = str(mapFile.readline()).strip("\n")
MainFrame.loadSource(MainFrame())
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="DICOM Toolkit", size=(800,705))
self.srcTc = wx.TextCtrl(self.panel, 131, '', size=(600,25), style=wx.TE_READONLY)
def loadSource(self):
self.srcTc.SetValue(MainFrame.sPath)
I eliminated most of the code and what's above is where it is giving me trouble. How do I change self.srcTc in the MainFrame class from either the Process class or a function in the MainFrame class? I am having trouble actually pointing to self.srcTc without a handler that stems from the MainFrame class.
There are several ways to accomplish this sort of thing. You can pass a handle to your panel class that can call whatever it needs in the parent to set the value (i.e. parent.myTxtCtrl.SetValue(val) ) or you can use pubsub. I personally recommend the latter as it's much more flexible and less prone to breakage as you change your program. I wrote the following tutorial that should get you up to speed: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
I think what you want has to look like something like that (without a working example):
class Process(wx.Panel):
def loadMap(self, event):
frame = MainFrame()
frame.sPath = str(mapFile.readline()).strip("\n")
frame.loadSource()
when using MainFrame.sPath = ... you're not actually changing sPath to a MainFrame you created, but to the class itself, then you create it, in MainFrame() without storing a reference to it (assign it to a variable for example). So, you can't access it from somewhere other than "inside" the class itself as self.
The solution is to create an instance of a MainFrame and operate on it. Once you create it and assign it to a variable, you can manipulate the .sPath attribute and call loadSource().
UPDATE: From you code snippet, it seems you create the MainFrame instance in the end of the file: MainFrame().Show(), and then in the loadMap method, you create a new one.
What you should do is this, in the end of your file:
app = wx.App(0)
#MainFrame().Show()
mainFrame = MainFrame() # or, insteadof making it a global variable, pass it as an argument to the objects you create, or store a reference to it anywhere else.
mainFrame.Show()
app.MainLoop()
and in the loadMap method:
def loadMap(self, event):
global mainFrame # or wherever you stored the reference to it
# ...
# remove this:
# mainFrame = MainFrame()
# set the sPath to the OBJECT mainFrame not the CLASS MainFrame
mainFrame.sPath = str(mapFile.readline()).strip("\n")
mainFrame.srcTc.SetValue(MainFrame.sPath)
Now this way, it should work.
The problem was that you are creating another frame, changing its path and updating its text, but you are not showing it. The correction is to store the actual window that is being shown, and update this one.