Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I position shapes and text on the tk.Canvas so they are not cut off?

I am using Tkinter's Canvas to create simple graphics for my GUI. I notice that I want to place my shapes and text right at the corners of my canvas, but they are ending up partially hidden. For text, I see there is an anchor option which the documentation suggests being set to NW if, for example, I want to place the text in the top left corner, but even then I see just a little bit of the beginning of the text being cut off. Here is my code:

import Tkinter as tk

root = tk.Tk()
root.geometry("300x300")
c = tk.Canvas(root, bg="green", width=300, height=300)
c.pack(fill="both", side="right", expand=True)
c.create_text(0,0,text="Hello world!", anchor="nw")

root.mainloop()

I know I can adjust the coordinates of where the text starts and by trial and error figure out which one gives the best looking result, but I was wondering if there was a smarter way to do it.

I notice a similar thing when I try to create shapes, such as a circle:

import Tkinter as tk

root = tk.Tk()
root.geometry("300x300")
c = tk.Canvas(root, bg="green", width=300, height=300)
c.pack(fill="both", side="right",expand=True)
c.create_oval(0,0,300,300, fill="gray")

root.mainloop()

For the circle, the parts of the circle closest to the edges are being cut off. If I stretch and drag the window to be larger, I can see the far right and bottom parts of the circle, so they are being draw. I also don't see an option similar to anchor for the circle.

I am noticing the tiniest amount of white space around my canvas, between the canvas and the window. I set the pack options to fill out against all sides and to expand if extra space was available. I wondering if this is the problem.

like image 836
Sebastian Freeman Avatar asked Dec 12 '25 03:12

Sebastian Freeman


1 Answers

Unfortunately, the canvas border and highlight ring are inside the widget and thus use some of the drawable area and can potentially hide parts of other objects.

The simplest solution is to set the highlightthickness and borderwidth attributes to zero:

c.configure(highlightthickness=0, borderwidth=0)

If you need a border and/or highlight ring, put the canvas inside a frame.

like image 150
Bryan Oakley Avatar answered Dec 14 '25 06:12

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!