Solution to tkinter Canvas drawing not showing in python

Solution to tkinter Canvas drawing not showing in python

1. The following is the unsuccessful drawing code

from tkinter import *
import math

WIDTH, HEIGHT = 510, 210
ORIGIN_X, ORIGIN_Y = 2, HEIGHT/2 #原点

SCALE_X, SCALE_Y = 40, 100 #x轴、y轴缩放倍数
ox, oy = 0, 0
x, y = 0, 0
arc = 0 #弧度
END_ARC = 360 * 2 #函数图形画两个周期

root = Tk()
c = Canvas(root, bg = 'white', width = WIDTH, height = HEIGHT)
c.pack()

c.create_text(200, 20, text = 'y = cos(x)')
c.create_line(0, ORIGIN_Y, WIDTH, ORIGIN_Y)
c.create_line(ORIGIN_X, 0, ORIGIN_X, HEIGHT)
for i in range(0, END_ARC+1, 10):
    arc = math.pi * i / 180
    x = ORIGIN_X + arc * SCALE_X
    y = ORIGIN_Y - math.cos(arc) * SCALE_Y
    c.create_line(ox, oy, x, y)
    ox, oy = x, y

Direct execution returns 0 and no picture is displayed
Insert picture description here

2. Solution

Add a line of code at the bottom:

root.mainloop()

The complete code is as follows:

from tkinter import *
import math

WIDTH, HEIGHT = 510, 210
ORIGIN_X, ORIGIN_Y = 2, HEIGHT/2 #原点

SCALE_X, SCALE_Y = 40, 100 #x轴、y轴缩放倍数
ox, oy = 0, 0
x, y = 0, 0
arc = 0 #弧度
END_ARC = 360 * 2 #函数图形画两个周期

root = Tk()
c = Canvas(root, bg = 'white', width = WIDTH, height = HEIGHT)
c.pack()

c.create_text(200, 20, text = 'y = cos(x)')
c.create_line(0, ORIGIN_Y, WIDTH, ORIGIN_Y)
c.create_line(ORIGIN_X, 0, ORIGIN_X, HEIGHT)
for i in range(0, END_ARC+1, 10):
    arc = math.pi * i / 180
    x = ORIGIN_X + arc * SCALE_X
    y = ORIGIN_Y - math.cos(arc) * SCALE_Y
    c.create_line(ox, oy, x, y)
    ox, oy = x, y

root.mainloop()

Then you can draw the picture
Insert picture description here

3. Reason

Between root and root.pack() is the type, size, style, and position of the designed component, and then bind an event. The mainloop enters the event (message) loop. Once the event is detected, the component is refreshed. That’s an online statement. My understanding is that if there is no mainloop, it will also draw, but the program will be closed after the drawing is completed, so it seems like there is no display. After adding the mainloop, it will monitor your behavior and close it. Will end the program. If anyone knows a better answer, please leave a message in the comment area.

Guess you like

Origin blog.csdn.net/weixin_43520670/article/details/111192321