Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python Tkinter Canvas canvas control

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Python Tkinter Canvas canvas control". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Python Tkinter Canvas canvas control.

Canvas control has two functions. First, it can be used to draw all kinds of graphics, such as arcs, lines, ellipses, polygons and rectangles, etc. Secondly, Canvas controls can also be used to display pictures (including bitmaps). We call these graphics drawn on canvas controls "canvas objects".

Each canvas object has a "unique identity ID" that Tkinter automatically creates for it, making it easy to control and manipulate these canvas objects.

Through the Canvas control to create a simple graphics editor, so that users can achieve the purpose of custom graphics, just like using a paintbrush to paint on the canvas, can draw a variety of shapes, so as to have a better human-computer interaction experience.

Basic properties of Canvas control

The following is a brief introduction to the common properties of the Canvas control, as shown in the following table:

Property method background (bg) specifies the background color of the Canvas control borderwidth (bd) specifies the border width of the Canvas control closeenough1. Specifies a distance that is considered to be over the canvas object when the distance between the mouse and the canvas object is less than this value

two。 This option is a floating-point type value confine1. Specifies whether the Canvas control allows scrolling beyond the scroll range set by the scrollregion option. The default value is Trueselectbackground, which specifies the background color when the canvas object (that is, graphics drawn on the Canvas canvas) is selected. Selectborderwidth specifies the border width when the canvas object is selected (check the border) selectforeground specifies the foreground color when the canvas object is selected, state sets the state of the Canvas: "normal" or "disabled", the default is "normal", note This value does not affect the state of the canvas object takefocus specifies that you can use the Tab key to move the focus to the input box, default is on, set this option to False avoid focus in this input box width specifies the width of the Canvas, in pixels xscrollcommand and scrollbar (scroll bar) control associated (along the x-axis horizontal direction) xscrollincrement1. This option specifies the step size of the horizontal scrolling of the Canvas

two。 For example,'3c 'means 3 centimeters, and the optional units are' i' (inches),'m' (millimeters) and'p' (DPI, about'1i 'equals' 72p')

3. The default is 0, which means that you can scroll horizontally to any position yscrollcommand is associated with the scrollbar control (scroll bar) (vertical along the y-axis) yscrollincrement1. This option specifies the step size of the vertical scrolling of the Canvas

two。 For example,'3c 'means 3 centimeters, and the optional units are' i' (inches),'m' (millimeters) and'p' (DPI, about'1i 'equals' 72p')

3. The default value is 0, which means you can scroll vertically to any position.

The above properties are used to set the Canvas control, and the following example defines a Canvas, as shown below:

Import tkinter as tkwindow = tk.Tk () window.title ("C language Chinese net") window.geometry ('400x200') # creation library does not allow you to change window.resizable (0L0) window.iconbitmap (' C:/Users/Administrator/Desktop/ C Chinese net logo.ico') # create canvas canvas = tk.Canvas (window, bg='#CDC9A5', height=200, width=300) canvas.pack () window.mainloop ()

The running result of the program is as follows:

Figure 1:tkinter Canvas control

Common drawing methods of Canvas controls

The Cansvas control provides a series of common methods for drawing geometry, which are briefly described below:

Create_line (x0, y0, x1, y1,..., xn, yn, options) 1. Create one or more segments based on the given coordinates

two。 The parameter x0quence y0rex1recovery1magent.dyn defines the coordinates of the line.

3. Parameter options represents other optional parameters create_oval (x0, y0, x1, y1, options) 1. Draw a circle or oval

two。 Parameters x0 and y0 define the upper-left corner coordinates of the drawing area, and parameters x1 and y1 define the lower-right corner coordinates of the drawing area.

3. The parameter options represents the other optional parameters create_polygon (x0, y0, x1, y1,..., xn, yn, options) 1. Draw a polygon with at least three points

two。 Parameters x0, y0, x1, y1,..., xn, yn define the coordinates of the polygon.

3. Parameter options represents other optional parameters create_rectangle (x0, y0, x1, y1, options) 1. Draw a rectangle

two。 The parameters x 0 and y 0 define the upper left corner coordinates of the rectangle, and the parameters x and y 1 define the lower right corner coordinates of the rectangle.

3. Parameter options represents other optional parameters create_text (x0, y0, text, options) 1. Draw a text string. Among them

two。 Parameters x0 and y0 define the upper-left coordinates of the text string, and parameter text defines the text of the text string.

3. The parameter options represents the other optional parameters create_image (x, y, image) 1. Create a picture

two。 The parameters x and y define the upper-left coordinates of the picture.

3. The parameter image defines the source of the picture, which must be an instance variable of the BitmapImage class of the tkinter module or the PhotoImage class. Create_bitmap (x, y, bitmap) 1. Create a bitmap

two。 The parameters x and y define the upper-left coordinates of the bitmap

3. The parameter bitmap defines the source of the bitmap. The parameter values can be gray12, gray25, gray50, gray75, hourglass, error, questhead, info, warning or question, or you can directly use a file of type XBM (X Bitmap). In this case, you need to add an @ symbol to the name of the XBM file, such as bitmap=@hello.xbmcreate_arc (coord, start, extent, fill) 1. Draw an arc

two。 The parameter coord defines the coordinates of the upper left corner and lower right corner of the curved block.

3. The parameter start defines the starting angle of the arc block (counterclockwise)

4. The parameter extent defines the end angle of the arc block (counterclockwise)

5. The parameter fill defines the color of the filled arc block.

Note: all of the above methods return a unique ID of a canvas object. With regard to the options parameter, the frequently used parameters are introduced through an example below. (however, because there are more optional parameters, and the parameters in each method are more or less the same, they are no longer enumerated one by one.)

It is not difficult to see from the above table that the Canvas control uses a coordinate system to determine each point in the canvas. In general, the default upper-left corner of the main window is the coordinate origin, this coordinate system is called the "window coordinate system", but there will also be another case, that is, the size of the canvas may be larger than the main window, when this happens, you can use the Canvas control with the scroll bar, at this time will take the upper-left corner of the canvas as the coordinate origin, we call this coordinate system "canvas coordinate system".

Draw a line

The following example shows how to draw a dashed and solid line on the canvas (the Canvas control) with the following code:

From tkinter import * root = Tk () # sets the background color of the canvas root.config (bg='#87CEEB') root.title ("C language Chinese net") root.geometry ('450x350') root.iconbitmap ('C:/Users/Administrator/Desktop/ C Chinese net logo.ico') # sets the background color of the canvas to white cv=Canvas (root,bg= "white", width = 300) Height = 250) # place the control in the main window cv.pack () # set coordinate points, where you can set coordinate points point= in tuple form [(10mem20), (20recovery30), (30recovery40), (40100), (80120), (150Power90)] # create the canvas Add the line # fill parameter to specify the color of the fill. If it is an empty string, the transparent # dash parameter represents the outline of the dashed line, and the tuple parameter represents the length of the dashed line segment and the interval between the line segments. # arrow sets the arrow style of the line segment, with no arrowhead by default. The parameter value first indicates the position of adding the arrow at the beginning of the segment, last indicates the position at the end, and both indicates the addition of # smooth Boolean parameters at both ends. Indicates whether to underline in the style of a curve. The default is False# width to control the lineweight line1=cv.create_line (point,fill= "purple", dash= (1Power1), arrow=LAST,width=5) print ('canvas id number of line segment line1:', line1) line2=cv.create_line (point,fill= "red", arrow=BOTH,smooth=TRUE,width=5) print ('canvas id number of line segment line2:', line2) # move one of the line segments Simply change its coordinates and use the coords () method to move the curve cv.coords (line2,50,30,25,35,35,40,50,120,60,170,10180) # display window root.mainloop ()

For the final result of running the program, see the following figure:

Figure 1:tkinter Canvas control

Some parameters are involved in the above example, such as fill, dash, arrow, etc. The following table gives a brief introduction to the parameters of the create_line () function:

Property description activedash when the canvas object state is "active", draw dotted line activefill when the canvas object state is "active", fill color activestipple when the canvas object state is "active", specify the filled bitmap activewidth when the canvas object state is "active", specify the width of the frame arrow1. The default segment does not have arrowheads. Add arrowheads to the segments by setting this option

2. "first" means to add an arrow to the beginning of the segment

3. "last" means to add an arrow to the end of the segment

4. "both" means to add an arrow arrowshape1 at both ends. Use a triple to specify the shape of the arrowhead. The default value is (8, 10, 3). The values in the tuple represent the length of the three sides of the arrow capstyle1. Specifies the style at both ends of the segment. The default value is "butt".

two。 The value of this option can be:

"butt" (two segments of a line are tangent at the beginning and the end)

"projecting" (the two segments of the line extend the length set by the width option by half at the start and end points respectively)

"round" (two segments of a line are extended by half of the length set by width at the start and end of the line and drawn with a fillet) dash draws a dashed line. The value of this option is an integer tuple, and the elements in the tuple represent the length and interval of the short line, for example, (3,5) represents a short line of 3 pixels and an interval of 5 pixels dashoffset specifies the offset position of the beginning of the dashed line, such as dash= (5, 1, 2, 1), dashoffset=3. Then draw the dotted line disableddash from 2 when the canvas object state is "disabled", draw the dotted line disabledfill when the canvas object state is "disabled", fill the color disabledstipple when the canvas object state is "disabled", specify the filled bitmap disabledwidth when the canvas object state is "disabled", specify the width of the frame fill1. Specifies the color of the fill, and an empty string represents a transparent joinstyle1. Specifies the style of the interface when drawing between two adjacent segments, default to "round"

two。 The value of this option can be:

"round" (fillet is drawn with the connection point as the center and the length set by the 1 width option as the radius)

"bevel" (slicing the angle between two segments at the connection point)

"miter" (extending to a point along the angle between the two segments) offset specifies that the offset smoothness of the bitmap when dotted mode is False, if set to True, it means that the drawn segment splinesteps will be replaced by the style of the curve when drawing the curve, this option specifies the number of broken lines to form the curve, the default value is 12, it should be noted that this option will take effect only when the smooth option is True. State specifies the state of the canvas object, the default is "normal", and the parameter values are "normal", "disabled" (not available), and "hidden" (hidden). Stipple specifies a bitmap to fill. The default value is an empty string, indicating that the solid tags tags the created canvas object width to specify the width of the border.

For fan, rectangle, triangle, circle, etc., these closed graphics are composed of two parts: outline line and fill color. When drawing these graphs, the optional parameters of the correlation function are also slightly different from those of the above table. Here is a brief introduction to the fan-shaped create_arc () function:

Property method activedash when the canvas object state is "active", draw dotted activefill when the canvas object state is "active", fill color activeoutline when the canvas object state is "active", draw outline activeoutlinestipple when the canvas object state is "active", specify the bitmap activestipple of the filled outline when the canvas object state is "active" Specify filled bitmap activewidth when the canvas object state is "active", specify the width of the border dash specifies the dashed outline drawn, dashoffset specifies the offset position of the beginning of the dashed outline disableddash when the canvas object state is "disabled", the dotted disabledfill is drawn when the canvas object state is "disabled", the fill color disabledoutline when the canvas object state is "disabled" Draw outline disabledoutlinestipple when the canvas object state is "disabled", specify the bitmap disabledstipple of the filled outline when the canvas object state is "disabled", specify the filled bitmap disabledwidth when the canvas object state is "disabled", specify the width of the border extent specify the span (the angle from the position specified by the start option to the end position) the default value is 90.0fill, which has the same meaning as the above table Indicates the specified fill color. If it is an empty string, offset specifies the offset of the fill position when drawing in dotted mode. The parameter values are "xPowery" coordinate offset and position offset. For example, "ne" / "e" outline specifies the color of the outline outlineoffset specifies the offset outlinestipple of the bitmap when the outline is drawn in dotted mode. When the outline option is set, this option is used to specify a bitmap to fill the frame. The default value is an empty string, indicating that the offset angle of the black start specified starting position style creates a sector by default, and specifies whether the method creates a sector ("pieslice"), a bow ("chord"), or an arc ("arc") tags tags the created canvas object width to specify the width of the border

The parameters often used in the actual use are dash, fill, outline, extend and start, but we can't remember all these parameters. It is a good way to check the manual at this time.

Let's take a set of simple examples of drawing geometry:

From tkinter import * root = Tk () # set the background color of the main window area to distinguish the color of the canvas area root.config (bg='#8DB6CD') root.title ("C language Chinese net") root.geometry ('500x400') root.iconbitmap (' C:/Users/Administrator/Desktop/ C Chinese net logo.ico') # set the canvas to white canvas = Canvas (root,width = 400 magnificent height = 400 magnificent white whiteite) # set the reference coordinates x0primex Y1 = 10, 10, 10, 80, 8, draw a fan with a starting angle of 0 degrees. The end angle is 270. the fan-shaped area is filled with light blue, the outline is blue, and the lineweight is 2pxarc = canvas.create_arc (x0, y0, x1, y1jue start = 0, extent = 270, fill ='# B0E0E6 parallel drawing = 'blue',width=2) # draw the circle oval = canvas.create_oval (x00E0E6 parallel drawing =' # CD950C',outline = 'blue',width=2) # draw the rectangle, and set the outline to transparent That is, it does not display the outermost outline, and defaults to black rect = canvas.create_rectangle (x0Magnec y0prim100memex1magnum 100magnum x1magnum 100pyrrine ='') # draw a triangle and fill the color as green trigon = canvas.create_polygon (80pint 80pingle 150phap200, outline= ", fill=" green ",) # of course, you can also draw an arbitrary polygon, as long as your coordinates are correct First define a series of coordinate points on polygons poly_points= [(0280), (140200), (140240), (270240), (270320), (140320), (140360)] polygon = canvas.create_polygon (poly_points,fill= "# BF3EFF") # place the canvas on the main window canvas.pack () # display window root.mainloop ()

The running result of the program is as follows:

Figure 2:tkinter drawing geometry

Note: the first two parameters of the create_rectangle () method determine the upper-left coordinates of the rectangle, and the last two parameters determine the lower-right coordinates of the rectangle; in addition, the create_oval () method can not only draw a circle, but also an oval, depending on the passed parameters.

In addition to drawing geometry, Tkinter can also display pictures, create bitmaps, and text information, as shown in the following example:

From tkinter import * root=Tk () # # set the background color of the main window area to distinguish the color of the canvas area root.config (bg='#8DB6CD') root.title ("C language Chinese net") root.geometry ('500x300') root.iconbitmap (' C:/Users/Administrator/Desktop/ C Chinese net logo.ico') # # set the canvas to white cv = Canvas (root,bg='white') # tkinter built-in bitmap name bitmaps = ["error" "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", "warning"] # list all bitmap styles for i in range (len (bitmaps)): # the first two parameters specify the location of a bitmap Then arrange cv.create_bitmap ((item1) * 30Magne30 reference bitmaps [I]) # and add text to the canvas # parameter description, the first two parameters (x0 ~ Y0) reference point, specify the upper-left coordinates of the text string # anchor specifies the relative position of the text to the reference point Specify the orientation, for example, cv.create_text such as W/E/N/S (30Magne80Text = "tkinter built-in bitmap preview", fill ='# 7CCD7Coctecience font = ('Microsoft yahei', 15penceBold') # display pictures Use PhotoImage () to load the picture img = PhotoImage (file= "C:/Users/Administrator/Desktop/c.biancheng.gif") cv.create_image (30Magne150 C:/Users/Administrator/Desktop/c.biancheng.gif image = img,anchor = W) cv.create_text (30Magne220) text = "Picture Preview", fill ='# 7CCD7C recording mainloop font = ('Microsoft Yahue', 15Coherbold`) cv.pack ()

The running result of the program is as follows:

Figure 3:tkinter Canvas control

Note that objects added to Canvas remain straight all the time. If you want to modify them, you can use the coords () and move () methods to move objects on the canvas, and of course you can use delete () to delete them, as shown in the example:

From tkinter import * root=Tk () # # set the background color of the main window area to distinguish the color of the canvas area root.config (bg='#8DB6CD') root.title ("C language Chinese net") root.geometry ('500x300') root.iconbitmap ('C:/Users/Administrator/Desktop/ C Chinese net logo.ico') # define the movement function def move_img (): # define the movement coordinate cv.move (image1,50,30) # # set the canvas to white cv = Canvas (root Bg='white') # use PhotoImage () to load the picture img = PhotoImage (file= "C:/Users/Administrator/Desktop/c.biancheng.gif") image1=cv.create_image (30Magne150 img,anchor = W) # place the button in the canvas btn=Button (cv,text= "Click to move canvas", bg= "# 8A8A8A", activebackground= "# 7CCD7C", command=move_img) # create a window control at the specified location Tags to add tags cv.create_window (365 cv.delete 250) cv.pack () # call delete () to delete canvas objects, if passed in, delete all canvas objects # cv.delete (image1) cv.pack () # display window root.mainloop ()

The running result of the program is as follows:

Figure 4: moving canvas objects

Note: the use of canvas controls allows users to draw their own drawings, but this can only be achieved in conjunction with the tkinter event mechanism.

Thank you for reading, the above is the content of "how to use Python Tkinter Canvas canvas control". After the study of this article, I believe you have a deeper understanding of how to use Python Tkinter Canvas canvas control, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report