What is the difference between a Frame and Canvas in tkinter? I'm a beginner in tkinter, and I don't really see any difference between the two... I've been using them interchangeably. Are they the same or is there some sort of internal or external difference?
A Frame is designed to be a container for other widgets. It really doesn't do anything but provide a border and color, and to collect a set of widgets into a logical group.
A Canvas is something that can act as a container for other widgets (as can just about any widget), but it also has features that let you draw circles, lines, rectangles, and other objects on it.
A Canvas can also be scrolled, whereas a frame cannot.
Related
(0) Introduction
Hello Everyone! I am an absolute beginner to Tkinter and not sure how to achieve my result. I tried several strategies and was disappointed multiple times. Didn't work due to my ignorance.
I am building my own little programming text editor.
I want to add functionality like yellow light bulbs in IntelliJ IDEA.
According to the idea, a yellow circle with a question mark appears on the screen next to a character which caused a syntax error in the code.
The question is not about positioning objects. I sort of confident in it. I am struggling with tk.Canvas imposing its background. I want to get rid of background and keep drawings visible.
(1) A "Naive" approach
In the code editor tk.Frame I have the following widgets:
tk.Text where user types code.
Positioned with .pack() method.
Line numbers tk.Canvas which is responsible for displaying line numbers.
Positioned with .pack() method
For each syntax error in the code I create a tk.Canvas object where I create yellow circle and question mark text.
Positioned with .place() method
It turned out, tk.Canvas _object has solid background which is covering half of the screen and looks ugly
(2) Attempted strategies, which failed
I looked for a way to make the Canvas object transparent, but from what I found, transparency is platform-dependent. Scary. I gave up.
I also tried to make the canvas have zero size with canvas.configure(width=0, height=0).
I was hoping that the canvas will become invisible and as a result, its objects will have a transparency illusion.
Unfortunately, Canvas objects, rectangles, circles and others are not displayed outside the canvas itself.
The image above is evidence of that property.
The circle is not displayed fully, because a part of it is outside the canvas rectangle.
(3) Some Ideas
I have a couple ideas, which haven't been attempted yet, due to the lack of confidence and research
3.1. Maybe Z-index hack ?
I hope, that It is possible to use a single tk.Canvas to store all circles.
The canvas will be placed in the same position as the text.
Tweaking z-indices, hopefully, can be done in such a way, that the canvas background will be "bellow" The text field, while the yellow circles will be "above" the text.
However. That Idea raises the following questions:
Does tkinter have absolute Z-indexing?
Do the Canvas objects (circles) share the same Z-index?
If so then I guess, the strategy is doomed and will fail. The Canvas is a widget, while as long as I know, canvas objects are not widgets.
3.2. Switch from Canvas approach to Images?
I heard that tk.Label can store Images.
I could draw a simple PNG of yellow circle with question mark. Maybe instead of canvas circle I could display these labels with images and use .place() to adjust their positions. Maybe worth trying.
(4) Summary of the question
How to hack tk.Canvas or achieve transparent background by keeking floating circles not transparent on top of a text? Thank you very much!
EDIT:
The target Platform is Linux.
Hence using root.wm_attrinutes("-transparentcolor", somecolor) hack doesn't work.
I want to eliminate strange extra space that seems to resist any size tweaking in my layout when using grid() alone, but calling in pack() sometimes make things worse: The GUI simply disappear entirely!
I read a few eye-opening layout answers from #Bryan Oakley such as:
When to use pack or grid layouts in tkinter?
and
Tkinter: grid or pack inside a grid?
but when I get down to write my own stuff, I still often have troubles.
My understanding:
I must have a Frame to fill the root window, otherwise there'd be no hope to fill the extra space in the window, however I tweak widgets alone.
For all the child widgets sitting inside a common parent Frame, I must use either pack() or grid() but not both.
When using grid() in a Frame, it's mandatory to specify Frame.grid_rowconfigure() and .grid_columnconfigure() with non-zero weight arguments. Otherwise, nothing would show up.
It's thus possible to have the main Frame using pack(), but its immediate child Frames all using grid(); Inside each of these child Frames on the grid, we could then pack() their own child widgets. In other words, we could interleave grid() and pack() by "regions" or container hierarchy levels, but never mix them in the same container: The only restriction.
By a careful weight design, I could fill a horizontal space in a parent Frame with a child Frame full of widgets laid out horizontally, e.g., all widgets use grid(sticky='nsew'), and the child Frame uses pack(side='top', fill='both', expand=True).
If my understanding was correct, then I could never figure out why #5 couldn't work for me, e.g., there is always unused extra space towards the right end of my horizontal child Frame inside the main Frame of the root window.
UPDATE 2
I figured it out. #5 didn't work for me because I forgot to specify .grid_columnconfigure(0, weight=1) in the main Frame before using grid(). My bad! Case closed.
UPDATE
I'm on macOS High Sierra, running python 3.6.4 Homebrew.
In what cases Tkinter's grid() cannot be mixed with pack()?
In all cases, you cannot use both grid and pack for widgets that have a common master. Within a master, all direct children must use the same geometry manager. Within an application as a whole, you can mix pack and grid all you want as long as you follow that one rule that you can't use them both for widgets that have the same parent.
I must have a Frame to fill the root window, otherwise there'd be no hope to fill the extra space in the window, however I tweak widgets alone.
This is not correct. You can easily fill all of the space in the root window without using a frame.
For all the child widgets sitting inside a common parent Frame, I must use either pack() or grid() but not both.
That is correct. The third option is to use place, though it's rarely the best choice.
When using grid() in a Frame, it's mandatory to specify Frame.grid_rowconfigure() and .grid_columnconfigure() with non-zero weight arguments. Otherwise, nothing would show up.
That is not true -- configuring rows and columns to have a non-zero weight isn't mandatory. It's usually a best practice, but it's not required in order for widgets to show up. The weight only applies to how grid manages extra space. Any widgets with a non-zero size should appear whether you use weights or not.
It's thus possible to have the main Frame using pack(), but its immediate child Frames all using grid()
Correct.
By a careful weight design, I could fill a horizontal space in a parent Frame with a child Frame full of widgets laid out horizontally, e.g., all widgets use grid(sticky='nsew'), and the child Frame uses pack(side='top', fill='both', expand=True).
That is correct.
I wanted to create an app which has an image as its background. But when I add a Label over the image, the label had a white background.
Is there a way to set the Label widget's background color to 'transparent'?
I'm not aware of a way to make Label backgrounds transparent. One alternative is to use a Canvas widget as the base for the whole thing, then use the create_image method to add the background image, and create_text to make the text labels. It will be a bit more work, but the text should render without a background on top of the image. (Admittedly I have very little experience with the Canvas widget, so I'm speaking more from theory than experience, but it's worth a try.)
If you don't have a good Tkinter reference, I highly recommend this one made by New Mexico Tech. It's available as a downloadable PDF as well.
What's the main difference between the Tkinter geometry managers grid and pack?
What do you use for your projects ?
If grid is better to align object, what the main purpose of pack?
grid is used to lay out widgets in a grid. Another answer says it "overlays a graph" which is a bit of a misnomer. It doesn't overlay anything, it merely arranges widgets along row and column boundaries. It is great for creating tables and other structured types of layouts.
pack lays things out along the sides of a box. It excels at doing layouts where everything is on a single row or in a single column (think rows of buttons in a toolbar or dialog box). It's also useful for very simple layouts such as a navigator on the left and a main work area on the right. It can be used to create very complex layouts but it gets tricky until you fully understand the packing algorithm.
You cannot use both grid and pack with widgets that have a common parent. Your app may work but it is much more likely to get into an infinite loop as each manager tries to layout the widgets, then the other notices the widgets change size and try to adjust, etc. etc.
The third manage is place. Place is great for doing either absolute positioning (ie: place widget at a given x/y) or relative (eg: place a widget on the right edge of some other widget).
While you cannot mix grid and pack within the same container (a container is typically a frame), you can use both grid and pack within a single application. This is very, very common since each has strengths and weaknesses. I use both on a regular basis.
I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background.
Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?
The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent.
However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame.
You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.
One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)
I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the place geometry manager. The place geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done.
... turned out to be unworkable because I wanted to add labels and more canvases to it, but I can't find any way to make their backgrounds transparent
If it is acceptable to load an additional extension, take a look at Tkzinc. From the web site,
Tkzinc (historically called Zinc) widget is very similar to the Tk Canvas in that they both support structured graphics. Like the Canvas, Tkzinc implements items used to display graphical entities. Those items can be manipulated and bindings can be associated with them to implement interaction behaviors. But unlike the Canvas, Tkzinc can structure the items in a hierarchy, has support for scaling and rotation, clipping can be set for sub-trees of the item hierarchy, supports muti-contour curves. It also provides advanced rendering with the help of OpenGL, such as color gradient, antialiasing, transparencies and a triangles item.
I'm currently using it on a tcl project and am quite pleased with the results. Extensions for tcl, perl, and python are available.
Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly.
COM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way.
QT will also let you do this in a similar manner.
GTK is slightly harder.