Tkinter Dynamic Widget editing - python

Here is my code:
class render_window:
def __init__(self, height, width, window_title):
self.root_window = Tk()
w = width
h = height
ws = self.root_window.winfo_screenwidth() # width of the screen
hs = self.root_window.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
self.root_window.title(window_title)
self.root_window.minsize(width, height)
self.root_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
def new_button(self, button_text, button_command="", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.button = ttk.Button(self.root_window, text=button_text, command=button_command)
self.button.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
def new_label(self, label_text, text_alignment="center", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.label = ttk.Label(self.root_window, text=label_text, anchor=text_alignment)
self.label.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
def new_progress_bar(self, pg_length=250, pg_mode="determinate", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.progress_bar = ttk.Progressbar(self.root_window, length=pg_length, mode=pg_mode)
self.progress_bar.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
def responsive_grid(self, row_responsive=0, column_responsive=0, row_weight_num=1, column_weight_num=1):
self.root_window.grid_columnconfigure(column_responsive, weight=column_weight_num)
self.root_window.grid_rowconfigure(row_responsive, weight=row_weight_num)
options_window = render_window(200, 250, "Options Window")
options_window.new_progress_bar()
options_window.progress_bar.start()
options_window.new_progress_bar(grid_column=1)
options_window.progress_bar.start()
options_window.new_label("Options Window\And other buttons...", grid_row=1, grid_columnspan=2)
options_window.root_window.mainloop()
I have created a system that allows the creation of an interface relatively easily using tkinter. I am having an issue with the modifying of already existing elements, I cannot seem to modify them if I create multiple instances, I can only edit the last one created. when I say modify/edit, I am talking about .config().
So whenever I do:
options_window.progress_bar.config(args_here), it only does that for the last bar created. Is there a way to specify which bar I can execute the code on?
Thanks!

If I understand you correctly... could you not just asign each progressbar to a variable? Ie.
pb1 = options_window.progress_bar
pb1.start()
pb1.conig('etc, etc')
Sorry if i have misunderstood your problem!
PS - Cool idea!

Related

Canvas.create_image(), draggable image seems not to be moving from its place?

Im working with Tkinter currently and im trying to make an draggable canvas image, the code i've "made"/edited from another stack overflow question, the second one to be particular. There code works for me when im using tk.Frame(), but it gives an error for Canvas.create_image(). So i edited it a little but now it seems to to be moving the image at all when i drag it
My code:
from tkinter import *
import pyautogui
x,y=pyautogui.size()
tk = Tk()
c = Canvas(tk, width=x, height=y)
c.place(x=-2,y=-3)
img = ImageTk.PhotoImage(PIL.Image.open(r"Data\backgrounds\background.jpg"))
c.create_image(0, 0, image=img, anchor=NW)
def command6():
print("command6")
def make_draggable(widget,btn="<Button-1>",motion="<B1-Motion>"):
def __draggable__(widget):
c.tag_bind(btn,btn,on_drag_start)
c.tag_bind(motion,motion,on_drag_motion)
def on_drag_start(event):
widget = event.widget
widget._drag_start_x = event.x
widget._drag_start_y = event.y
def on_drag_motion(event):
widget = event.widget
x = widget.winfo_x() - widget._drag_start_x + event.x
y = widget.winfo_y() - widget._drag_start_y + event.y
widget.move(widget,x, y)
__draggable__(widget)
APP_6 = r'apps\File.png'
APP_6 = PIL.Image.open(APP_6)
APP_6 = APP_6.resize((48,48),PIL.Image.ANTIALIAS)
APP_6 = ImageTk.PhotoImage(APP_6)
image_6 = ImageTk.PhotoImage(PIL.Image.open(r"apps\File.png"))
image_id_6 = c.create_image(48,48, image=APP_6)
c.move(image_id_6, 1,y-735)
c.tag_bind(image_id_6, '<Button-1>',command6)
make_draggable(image_id_6)
tk.mainloop()
this gives no errors or any unwanted output in the console.
There are few issues inside make_draggable() function:
first argument of .tag_bind() is the item ID of a canvas item. For your case, it is widget argument of make_draggable(). So the following lines:
c.tag_bind(btn,btn,on_drag_start)
c.tag_bind(motion,motion,on_drag_motion)
should be changed to
c.tag_bind(widget, btn, on_drag_start)
c.tag_bind(widget, motion, on_drag_motion)
Same apply to c.move(...) inside on_drag_motion()
the logic/calculation on moving the canvas item is wrong
Below is the modified make_draggable() function:
def make_draggable(widget, btn="<Button-1>", motion="<B1-Motion>"):
def __draggable__(widget):
c.tag_bind(widget, btn, on_drag_start)
c.tag_bind(widget, motion, on_drag_motion)
c._item_id = widget # save the item ID for later use
def on_drag_start(event):
widget = event.widget
# get the top-left coordinates of the selected item
x, y, *_ = widget.bbox(widget._item_id)
# save the offset of current mouse position from the top-left coordinates
widget._dx = event.x - x
widget._dy = event.y - y
def on_drag_motion(event):
widget = event.widget
# calculate the top-left coordinates of the item that the item to be moved to
x = event.x - widget._dx
y = event.y - widget._dy
# move the item using moveto() instead of move()
widget.moveto(widget._item_id, x, y)
__draggable__(widget)
As the above logic applies only on the item of the last call of make_draggable(). It is better to use class instead of function:
class make_draggable():
def __init__(self, item_id, btn="<Button-1>", motion="<B1-Motion>"):
self.item_id = item_id
c.tag_bind(item_id, btn, self.on_drag_start, add=True)
c.tag_bind(item_id, motion, self.on_drag_motion, add=True)
def on_drag_start(self, event):
x, y, *_ = event.widget.bbox(self.item_id)
self.dx, self.dy = event.x-x, event.y-y
def on_drag_motion(self, event):
event.widget.moveto(self.item_id, event.x-self.dx, event.y-self.dy)

Passing a tkinter canvas between classes without calling the child from within the parent

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.

Trouble calling a function from a class to draw an oval in Python

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()

how to create rectangles by getting scale values at the time in tkinter?

I want to get the value of a scale and create rectangles as many as the value is. For example, if I adjust the scale to number 7, 7 rectangles would be created next to each other, and after that if I adjust the scale value to 3, the rectangles shown in the canvas decreases to three at that moment. I had used the code below:
from tkinter import *
from tkinter import ttk
class rect:
def __init__(self, root):
self.root = root
self.size = IntVar()
self.canvas = Canvas(self.root, width=800, height=300)
self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size)
self.show()
def show(self):
x = 50
y = 50
for i in range(self.scale.get()):
self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red')
x += 50
self.canvas.pack()
self.scale.pack()
root = Tk()
a = rect(root)
root.mainloop()
I guess I have to use trace method, But I don't know how to.
Can anyone fix the code I used in the way which I explained.
Thank you.
One solution is to bind to <ButtonRelease>, and call your show method there. Since event bindings pass an object representing the event, you'll need to make that an optional argument if you also want to call show without any arguments.
For example:
class rect:
def __init__(self, root):
...
self.scale = Scale(...)
self.scale.bind("<ButtonRelease>", self.show)
I'm guessing you'll want to remove any previously drawn rectangles, so you'll need to call delete before creating the rectangles:
def show(...):
self.canvas.delete("all")
...

Delete an instance of a class

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.

Categories