[Tutor] Tkinter and canvas question

Alan Gauld alan.gauld at yahoo.co.uk
Tue Apr 18 03:39:05 EDT 2017


On 18/04/17 00:13, Phil wrote:
> Thank you for reading this.
> 
> How do I reference the_canvas from my solve() method? 

> class Sudoku(Frame):
>     def __init__(self, parent):
>         Frame.__init__(self, parent)
>         self.parent = parent
> 
>         parent.title("Sudoku solver")    
>         
>     	#create canvas
>         the_canvas = Canvas(width = 300, height = 300)                                         
>         the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)

You need to store the_canvas as an instance attribute so you need to
precede it with self:

self.the_canvas = Canvas(width=300, height=300


>     	#create grid
>                 
>         #create solve button
>         solve_button = Button(the_canvas, text = "Solve", command = self.solve,
>                                                                 anchor = W)

Similarly with the button

self.solve_button = ....

>         solve_button.configure(width = 5, activebackground = "#33B5E5",
>                                                             relief = FLAT)
>         solve_button.pack(side = TOP)
>         solve_button_window = the_canvas.create_window(250, 250, anchor=NW, window=solve_button)

Without the self your widgets are attached to local variables
that go out of scope as soon as init() ends. You could find
them by traversing the child widget tree of self.parent,
but that's just making life difficult for the sake of it!


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list