I am making a chess program and I want to be able to drag the pieces. In order to do this, I put the image of the piece on a Canvas
so it can be dragged (I can also use a Label
if I want). However, when I drag the piece there is a white square that surrounds the image of the piece.
When I researched the problem, many people gave this solution:
drag_canvas = Canvas(self, height=80, width=80, bg="yellow")
root.wm_attributes("-transparentcolor", "yellow")
This caused the background to be transparent but it was not the chessboard that was visible, it was the program behind the GUI
.
Is there any way I can have the background be transparent and show the chessboard behind rather than the program behind the tkinter window?
Note: I do not mind using any other widget (e.g. a Label
) but they must use modules that come default with Python (so no PIL) as this program needs to be used in an environment where I cannot download other modules.
Tkinter window provides many inbuilt functions and properties to help an application work seamlessly. They configure the GUI of the application as well. If we want to create a transparent window in an application, then we should have to define the color in the attributes ('-transparentcolor', 'color' ) method.
To create a transparent window, we will use the attributes () method. To create a transparent background, we need to use the -alpha argument in the attributes () method. The alpha is Used for transparency.
You can use transparent image to simulate the result. Use Pillow to create transparent image and then use canvas.create_image (...) to draw it. Below is a sample code:
Wxpython has good support for transparent image,and may be a better choice. For me there has never been a choice i find wxpython much better than Tkinter. The ugly look of Tkinter in windows is not ok at all. PyQt and pyGTK shold also has support for this.
Question: How to make a tkinter canvas background transparent?
The only possible config(...
option, to set the background to nothing
c.config(bg='')
results with: _tkinter.TclError: unknown color name ""
To get this result:
you have to hold the chess board and figures within the same .Canvas(...
.
self.canvas = Canvas(self, width=500, height=200, bd=0, highlightthickness=0)
self.canvas.create_rectangle(245,50,345,150, fill='white')
self.image = tk.PhotoImage(file='chess.png')
self.image_id = self.canvas.create_image(50,50, image=self.image)
self.canvas.move(self.image_id, 245, 100)
Tested with Python: 3.5 - TkVersion: 8.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With