I have taken this code from a larger program, and stripped out almost everything so as to illustrate the core of the problem.
The program is used to create multiple "rooms" that initially have the same attributes, but are later changed such that they are two separate objects.
To create two completely independent Room objects, I have tried to use copy.deepcopy(), but this gives: "TypeError: cannot pickle '_curses.window' object"
import curses
from curses import wrapper
import copy
def main(stdscr):
bg = Background(100, 237)
test_room = Room(10, 15, bg)
new_room = copy.deepcopy(test_room)
print("Test deepcopy: ", new_room.height, new_room.width) ### See if attributes copied successfully
class Background():
def __init__(self, height, width):
self.height = height
self.width = width
self.pad = curses.newpad(self.height, self.width)
class Room():
def __init__(self, height, width, background):
self.height = height
self.width = width
self.bg = background.pad
self.pad = background.pad.subpad(self.height, self.width)
### def __deepcopy__(self, memo)
###return self
while True:
curses.wrapper(main)
I see that the problem is with the self.bg and self.pad lines in the Room class; if these are commented out it works in all other respects, but obviously I need these lines for it to do what I need it to do. I tried defining my own deepcopy method (see commented out in Room class below), but I don't really understand how to use it properly and it doesn't appear to solve the problem.
I get that I am probably making multiple mistakes. What am I doing wrong, and what would be a better solution?
Related
I am somewhat of a beginner when it comes to Python, but i decided i want to write a basic 2-d physics playground. Unfortionetly i ran straigt into trouble when trying to setup the basic structure.
My plan is to create a GUI with a canvas in a parent function named mainWindow, then i figured i would create a child class (Hero) which creates a circle the user can manipulate on the canvas. This seems to work fairly well.
The problem occurs when i try to do anything with the Hero class, like call a function to delete the circle so i can redraw it in some direction. I can't seem to pass the canvas from the mainWindow to the Hero class. Any help would be greatly appreciated, including telling me that this is the wrong way to do things.
Im adding the two documents im working with since my rambling is probably hard to follow.
I run the program from the phesics.py document, resulting in the GUI poping up with my canvas and a red circle. When i close the window i get the following error:
classes.py", line 29, in moveHeroBody
canvas.delete(heroBody)
NameError: name 'canvas' is not defined
Unfortionetly i dont know how to get the "world" into the child
classes.py
from tkinter import *
class mainWindow():
def __init__(self):
#Setup the GUI
root = Tk()
root.geometry('800x600')
# Setup the canvas within the GUI (master)
world = Canvas(root, height = 600, width = 800, bg = "#FFFFFF")
world.place(relx = 0.5, rely = 0.5, anchor = CENTER)
Hero(world)
root.mainloop()
class Hero(mainWindow):
def __init__(self,world):
#Initial creation of hero at coordinates
x1 = 10
y1 = 10
x2 = 70
y2 = 70
heroBody = world.create_oval(x1,y1,x2,y2, fill = "#FF0000", outline = "#FF0000")
#Move the hero
def moveHeroBody():
print("moveHeroBody")
world.delete(heroBody)
phesics.py
from tkinter import *
from classes import *
mainWindow1 = mainWindow()
moveHero = Hero.moveHeroBody()
You're passing it ok, but you're throwing the value away. Also, Hero shouldn’t inherit from mainWindow.
You need to save world as an attribute so that you can reference it later.
class Hero():
def __init__(self,world):
self.world = world
...
Then, you can use self.world to reference the canvas:
def moveHeroBody():
print("moveHeroBody")
self.world.delete(heroBody)
Though, the above code will fail because heroBody is a variable local to the __init__ - you need to do the same with it:
class Hero():
def __init__(self,world):
self.world = world
...
self.heroBody = world.create_oval(...)
#Move the hero
def moveHeroBody():
print("moveHeroBody")
self.world.delete(self.heroBody)
I think you need to initialize the class Hero in your mainWindow class. The modifications needed to do in the code are:
classes.py
from tkinter import *
from time import sleep
class mainWindow():
def __init__(self):
#Setup the GUI
self.jump_gap = 25
root = Tk()
root.geometry('800x600')
# Setup the canvas within the GUI (master)
self.world = Canvas(root, height = 600, width = 800, bg = "#FFFFFF")
self.world.place(relx = 0.5, rely = 0.5, anchor = CENTER)
self.hero = Hero(self.world)
self.world.pack()
root.bind("<space>",self.jump) # -> [1] Binds the SPACE BAR Key to the function jump
root.mainloop()
def jump(self,event):
gaps = list(range(self.jump_gap))
for i in gaps:
self.world.after(1,self.hero.moveHeroJump(h=i)) # [2] -> Binds the moveHeroJump method with the window action to a queue of updates
self.world.update() #[2] updates the canvas
sleep(0.01*i) # Added some linear wait time to add some look to it
gaps.reverse()
for i in gaps:
self.world.after(1,self.hero.moveHeroJump(h=-i))
self.world.update()
sleep(0.01*i)
class Hero():
def __init__(self,world):
#Initial creation of hero at coordinates
self.world = world
self.x1 = 10
self.y1 = 410
self.x2 = 70
self.y2 = 470
self.heroBody = self.world.create_oval(self.x1,self.y1,self.x2,self.y2, fill = "#FF0000", outline = "#FF0000")
#Move the hero
def moveHeroJump(self,h):
print("moveHeroBody")
self.y1 -= h
self.y2 -= h
self.world.delete(self.heroBody)
self.heroBody = self.world.create_oval(self.x1,self.y1,self.x2,self.y2, fill = "#FF0000", outline = "#FF0000")
physics.py
from tkinter import *
from classes import *
mainWindow1 = mainWindow()
Edit
So this got me playing some minutes ago, and I researched some sources from stack in order to complete this question. Here are the sources (referenced in the code as well):
How to bind spacebar key to a certain method in tkinter python
Moving Tkinter Canvas
The solution edited above is capable to perform a simple animation of a ball jumping. self.jump_gap is a fixed quantity that tells the ball how much does it needs to jump. The jump parses a certain height h to the moveHeroJump method to make the ball change its position, after the change of position is queued into the Canvas an update is called to see the changes on the ball.
Beginner here trying to make sense of classes. Below is the code for my class Cell:
import tkinter
import random
top = tkinter.Tk()
canvas = tkinter.Canvas(top, bg="grey", height=400, width=400)
canvas.pack()
class Cell:
def __init__(self, x, y, r):
self.x = random(x)
self.y = random(y)
self.r = 200
def show(self):
canvas.create_oval(self.x, self.y, self.r, self.r, fill = "blue")
top.mainloop()
I'm attempting to draw the cell in my main program by calling the function show from the class. Here is the code for my main window:
import tkinter
top = tkinter.Tk()
canvas = tkinter.Canvas(top, bg="grey", height=400, width=400)
canvas.pack()
from Cell import Cell
cell = Cell()
cell.show()
top.mainloop()
This is resulting in the canvas being drawn correctly, but the oval is nowhere to be found. I am not getting any errors either.
Any help would be appreciated. Thank you!
====================
Turns out, I misunderstood the arguments for create_oval. I found some code that converts the clunky create_oval function into a function which receives a set of coordinates for the center of the oval and a radius.
In addition to this, the help I received in understanding classes and other Python functionality helped significantly as well. Thanks to those who helped!
This is my revised code which works as intended.
import tkinter as tk
import random
top = tk.Tk()
canvas = tk.Canvas(top, width=400, height=400, bg="grey")
canvas.grid()
def _create_circle(self, x, y, r, **kwargs):
return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle = _create_circle
class Cell:
def __init__(self, canvas, x, y, r):
self.canvas = canvas
self.x = x
self.y = y
self.r = r
def show(self):
self.canvas.create_circle(self.x, self. y, self.r, fill = "blue")
cell = Cell(canvas, random.randrange(50, 350), random.randrange(50, 350), 25)
cell.show()
top.mainloop()
The problem here is that your main script and your Cell module are both creating a new Tk instance, adding a Canvas to it, and then calling its mainloop method.
If you trace through the order in which statements get executed, you'll find that the cell = Cell() and cell.show() don't happen until after the first top.mainloop() returns, and mainloop() doesn't return until you quit the program. (In fact, if your code did get that far, it would fail with a TypeError, which I'll get to below.)
But, more generally, you only want one Tk in your program, and everyone else should refer to that.
And, in this case, you want the same for the Canvas: just one of them, packed onto the one Tk main window.
So, how can Cell.show refer to the canvas global from another module?
The best solution is to not refer to it as a global at all, and instead pass it in to the initializer, the same way you do with x, y, and r:
class Cell:
def __init__(self, canvas, x, y, r):
self.canvas = canvas
self.x = random(x)
self.y = random(y)
self.r = 200
def show(self):
self.canvas.create_oval(self.x, self.y, self.r, self.r, fill = "blue")
And then in the main script:
cell = Cell(canvas, ?, ?. ?)
cell.show()
But notice those ?s I put there. Your Cell class definition demands x, y, and r values in its initializer, but your Cell() constructor call doesn't pass any. That will raise a TypeError complaining that you're missing required arguments.
What do you want to pass here? Since the canvas is 400x400, maybe you want to pass something like 400, 400, 200? If so:
cell = Cell(canvas, 400, 400, 200)
cell.show()
Going back to that initializer, you've got some other problems there:
self.x = random(x)
self.y = random(y)
That random is a module. You can't call a module. You probably wanted something like this:
self.x = random.randrange(x)
That calls a function from the random module, one which is defined to return a random number in range(0, x), which seems like what you want.
Also:
self.r = 200
Why take an r parameter, just to ignore it? You probably wanted this:
self.r = r
Or, maybe you didn't actually want x, y, and r as parameters? Maybe you want to hardcode randrange(400), randrange(400), and 200, or maybe you want to compute them from the width and height of the canvas parameter, or… you can do almost anything you want, you just have to think through what you want, and make sure the interface you declare in the def matches the way you call it in the Cell(…) later.
I think your execution path is never getting to the cell.show() line.
When you import Cell, you have code at the top level top.mainloop(). This enters the main loop and never exits, so you never get to the lines below it.
It's a good rule of thumb to avoid putting code at the base level. Leave that for defining classes and functions. If you want code to run when the file is called like a script, put it in a if __name__ == __main__: condition.
You also had some syntax issues using random and calling the Cell constructor.
The example below works as expected.
import tkinter
import random
top = tkinter.Tk()
canvas = tkinter.Canvas(top, bg="grey", height=400, width=400)
canvas.pack()
class Cell:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def show(self):
canvas.create_oval(self.x, self.y, self.r, self.r, fill = "blue")
if __name__ == "__main__":
cell = Cell(100, 50, 5)
cell.show()
top.mainloop()
I've already asked a similar question here and I received quite a helpful reply.
But since then I've modified my code, now it is more optimized I guess, it is supposed to be more flexible, but the same problem persists. I can not delete an instance of the class.
What I'm trying to do is to create a circle (on a left-click) and then I expect the program to delete the circle (on a right-click).
My code:
from tkinter import *
class Application:
def __init__(self):
self.fen = Tk()
self.fen.title('Rom-rom-roooooom')
self.butt1 = Button(self.fen, text = ' Quit ', command = self.fen.quit)
self.can1 = Canvas(self.fen, width = 300, height = 300, bg = 'ivory')
self.can1.grid(row = 1)
self.butt1.grid(row = 2)
self.fen.bind("<Button-1>", self.create_obj)
self.fen.bind("<Button-3>", self.delete_obj)
self.fen.mainloop()
def create_obj(self, event):
self.d = Oval()
self.can1.create_oval(self.d.x1, self.d.y1, self.d.x2, self.d.y2, fill='red', width = 2)
def delete_obj(self, event):
self.can1.delete(self.d)
class Oval:
def __init__(self):
self.x1 = 50
self.y1 = 50
self.x2 = 70
self.y2 = 70
appp = Application()
so, once again, the problem is that here I can not delete the object:
def delete_obj(self, event):
self.can1.delete(self.d)
One more question. Given the fact that I'm just a begginer I don't know if I chose the right approach as far as class organisation is concerned. Does it look like a well-organized code or should I change anything at this stage already?
These two lines:
self.d = Oval()
self.can1.create_oval(self.d.x1, self.d.y1, self.d.x2, self.d.y2, fill='red', width = 2)
create a new Oval object, assign that object to the name self.d, then create an oval on self.can1 that is completely unrelated (aside from having the same dimensional attributes) from the Oval object assigned to self.d. Instead, I think you want:
o = Oval()
self.d = self.can1.create_oval(o.x1, o.y1, o.x2, o.y2, fill='red', width = 2)
This retains a reference to the object on the Canvas, so you will be able to delete it. Note that Oval is more-or-less-completely pointless, as all it does is provide the dimensions.
I have a problem with deleting canvas object from class.
I created an object of type Rectangle called f. Then I need to delete this object. Python deletes f, but does not delete a canvas object, which is on Frame. I don't know where is the problem.
from tkinter import *
class Rectangle():
def __init__(self, coords, color):
self.coords = coords
self.color = color
def __del__(self):
print("In DELETE")
del self
print("Goodbye")
def draw(self, canvas):
"""Draw the rectangle on a Tk Canvas."""
print("In draw ")
print("Canvas = ",canvas)
print("self = ",self)
print("bild canvas = ",canvas.create_rectangle(*self.coords, fill=self.color))
root = Tk()
root.title('Basic Tkinter straight line')
w = Canvas(root, width=500, height=500)
f = []
f = Rectangle((0+30*10, 0+30*10, 100+30*10, 100+30*10), "yellow")
print("Draw object", f.draw(w), f)
f.__del__()
del f
w.pack()
mainloop()
Ok, the problem you are having is you started creating a Rectangle object for your own use, which seems reasonable, but you need to work on its implementation.
Anyways to accomplish what you want to do simply (without your object):
# draws a rectangle and returns a integer
rectangle_id = c.create_rectangle(*(0, 0, 30, 30), fill="yellow")
c.delete(rectangle_id) # removes it from the canvas
To accomplish what you want with your Rectangle object I suggest using an attribute to store the id when you drew it and implement a method that can delete it. It looks like you may want to use the __del__ method to remove it when there are no longer any references to your object. This can be done, but you should be aware of some caveats (outside of the scope of my answer... See: http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/). I personally would opt for explicitly calling a method to delete the object representation from the view to avoid all that nonsense :).
There are many design decisions here I am ignoring, I suggest you put some thought into your use of OO here, or avoid it until you have better understanding of tkinter.
I created a class containing a method to position a window anywhere on the screen. I am using PyQt4 for GUI programming. I wrote following class:
from PyQt4 import QtGui
class setWindowPosition:
def __init__(self, xCoord, yCoord, windowName, parent = None):
self.x = xCoord
self.y = yCoord
self.wName = windowName;
def AdjustWindow(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
This code needs correction. Any file that imports this class will pass three parameters: desired_X_Position, desired_Y_position and its own name to this class. The method AdjustWindow should accept these three parameters and position the calling window to the desired coordinates.
In the above code, though I have passed the parameters, but not following how to modify the AdjustWindow method.
It is not entirely clear what you are trying to ask, But, you access the values in the method the same way you set them in the constructor.
from PyQt4 import QtGui
class setWindowPosition:
def __init__(self, xCoord, yCoord, windowName, parent = None):
self.x = xCoord
self.y = yCoord
self.wName = windowName;
def AdjustWindow(self):
print self.x, self.y, self.wName //See Here
//now use them how you want
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
EDIT:
I found this page which seems to be where you grabbed the code from.
Your class is not inheriting from QtGui.QWidget so calls to geometry() and move() are going to fail. Once you do that, it looks like it the code would be:
def AdjustWindow(self):
self.move(self.x, self.y)
However, you still need to figure out how to have your class as the one that controls the window with windowName. It seems like this package is for making GUIs and not controlling external windows. I could be wrong as I have only read enough to make this answer.