[Tutor] Tkinter and canvas question

boB Stepp robertvstepp at gmail.com
Mon Apr 17 23:57:41 EDT 2017


Sorry for the unnecessary post with no response -- inadvertent click
on "Send" button which was too near Gmail's "..." button to expand
content.

On Mon, Apr 17, 2017 at 6:13 PM, Phil <phil_lor at bigpond.com> wrote:
> Thank you for reading this.
>
> How do I reference the_canvas from my solve() method? Despite hours of searching I haven't been able to solve this or find a similar example. All that I've gained is a headache.
>

I have yet to do much class writing with tkinter, but if I am
understanding things correctly, in your Sudoku class where you
instantiate a Canvas instance, you assign it to the name "the_canvas".
This will be local to the __init__ method's namespace.  I think you
need to precede each of those "the_canvas" with "self." to get
"self.the_canvas".  This way your solve method will be able to access
it.

> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
>     return self.func(*args)
>   File "/home/pi/sudoku.py", line 64, in solve
>     self.the_canvas.create_text(20,20,text="5")
> AttributeError: 'Sudoku' object has no attribute 'the_canvas'
>
> from tkinter import *
>
> 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)
>
>         #create grid
>
>         #create solve button
>         solve_button = Button(the_canvas, text = "Solve", command = self.solve,
>                                                                 anchor = W)
>         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)
>
>     def solve(self):
>         print("solve called")
>         self.the_canvas.create_text(20,20,text="5")
>
>
> def main():
>     root = Tk()
>     app = Sudoku(root)
>     app.mainloop()
>
> if __name__ == '__main__':
>     main()
>
>
> --
> Regards,
> Phil
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
boB


More information about the Tutor mailing list