I would like to create a rectangle with rounded corners. I'm using canvas from tkinter.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
There seems not to be a built-in method for this. The closest thing would be a polyline with
smooth=1
, but that still looks more like an old TV screen, with the sides also slightly curved.Instead, you could define a helper function, combining the rounded rectangle from lines and arcs:
Example:
You could also provide another
**options
parameter to set line width, color etc. for the individual parts, but the problem with this is that e.g. lines and arcs are using different parameters for the line color (fill
andoutline
respectively). Also, if you want to have a filled rounded rectangle, you will have to specify that as a second method, using multiple rectangles.Offering an alternate approach to tobias's method would be to indeed do it with one polygon.
This would have the advantage of being one canvas object if you are worried about optimization, or not having to worry about a tag system for referring to a single object.
The code is a bit longer, but very basic, as it is just utilizing the idea that when smoothing a polygon, you can give the same coordinate twice to 'stop' the smooth from occuring.
This is an example of what can be done:
Using this function, you can just provide the normal coordinates that you would to a rectangle, and then specify the 'radius' which is rounded in the corners. The use of
**kwargs
denotes that you can pass keyword arguments such asfill="blue"
, just as you usually could with acreate_
method.Although the coords look complex, it is just going around methodically to each point in the 'rectangle', giving each non-corner point twice.
If you didn't mind a rather long line of code, you could put all the coordinates on one line, making the function just 2 lines(!). This looks like:
This produces the following (Note in mind this is ONE canvas object):