[Tutor] Tkinter custom widgets
David
bouncingcats at gmail.com
Sun Feb 12 21:29:31 EST 2023
On Mon, 13 Feb 2023 at 12:20, Phil <phillor9 at gmail.com> wrote:
> I've been investigating how I might create a custom widget class that
> contains a draw_circle method. Creating a draw_circle method is a
> straight forward task, however, positioning the resulting circle with
> .grid() seems to be logically impossible because the draw method
> requires a position.
Not so. The draw method will require a relative position *inside* the
Canvas widget. Which is unrelated to where the widget itself gets drawn.
> I see that a custom widget class is a sub class of frame and further,
> the custom widgets are based on existing Tkinter widgets. Creating a
> widget from scratch seems to be a complex, if not impossible, task for
> the unskilled.
Just combine the components you need.
> I'd like to postilion a button with the grid method and then position a
> custom widget circle in an adjacent cell. Maybe I could create a small
> canvas, or several small canvases, then draw the circle on a canvas and
> use grid() to position the canvas beside the button? It seems possible
> but messy.
This is the way. Demo executable code example:
#!/usr/bin/python3
import tkinter as tk
def canvas_create_circle(canvas, x, y, r):
# canvas = parent
# x,y = centre
# r = radius
x0 = x - r
y0 = y - r
x1 = x + r
y1 = y + r
canvas.create_oval(x0, y0, x1, y1, width=2)
class CustomWidget(tk.Frame):
def __init__(self, text, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
canvas = tk.Canvas(self, bg="white", width=80, height=80)
canvas_create_circle(canvas, 40, 40, 20)
canvas.grid(row=0, column=1)
btn = tk.Button(self, text=text)
btn.grid(row=0, column=0)
if __name__ == "__main__":
root = tk.Tk()
cw1= CustomWidget("cw1", root)
cw1.pack()
cw2= CustomWidget("cw2", root)
cw2.pack()
root.mainloop()
More information about the Tutor
mailing list