Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incorrect value returned by tkinter method canvas.winfo_width

I’ve just started learning how to create a game with tkinter. I found it so difficult to find information for all the available methods in the module. This website seemed comprehensive but was difficult to navigate to find relevant info for a specific method (for example winfo_width). I then tried to find the purpose of the method in question (winfo_width) by running an example. However, the returned value didn’t make sense as shown below

>>> import tkinter as tk
>>> root = tk.Tk()
>>> canvas = tk.Canvas(root, width=300, height=200)
>>> canvas.pack()
>>> rect = canvas.create_rectangle(50, 50, 150, 150, fill="red")
>>> print(canvas.winfo_width())
304  # should be 300, as specified in line 3

Could you please explain why the returned value was 304 instead of 300, and what is the best resource to find info for all available methods in the tkinter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The canvas has multiple options that affect its size. On my machine I get a size of 306, which represents the 300 pixels specified for the canvas, 0 pixels of borderwidth, and 3 pixels for highlightthickness. If you want the answer to be exactly 300, you need to explicitly set both the borderwidth and highlightthickness to zero. Your system apparently has different defaults for borderwidth and highlightthickness than my system does.

canvas = tk.Canvas(root, width=300, height=200, bd=0, highlightthickness=0)

The best resource for all of the options is the tcl/tk manual pages. The documentation there is the canonical documentation for the tk widgets.

It requires a slight mental translation from tcl to python, but the python docs (Tkinter Life Preserver) cover that.

From an interactive prompt you can use help. For example, help(tk.Canvas) will give you lots of information, though it’s tedious to wade through it. You can also use the configure method to get a lost of all options and their current values:

>>> print("\n".join([str(item) for item in canvas.configure().items()]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading