如何优化这个类似Tkinter“MS Paint”的程序?

2024-09-30 20:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在Tkinter的“画画”程序上工作了一段时间,但我的性能有问题。我不得不设置一个200毫秒的延迟来重新绘制,因为没有它它就无法真正运行。它必须使用这个网格系统,以便我可以轻松地将其发送到后端

它在第一次或第二次冲程时运行良好,但之后会占用大量CPU周期,无法使用

你们能施展你们的魔法,教我如何改进吗

我移除了大部分无用的东西:

from tkinter import Tk, Canvas, NW, NE, N

fen = Tk()
fen.geometry("1380x740")
fen.title("Dessine moi un mouton !")

c_width = 800
c_height = 600
couleur = "red"
epaisseur= 10

sdessin = Canvas(width = c_width, height = c_height, bg ='white')

board = []
for i in range(0, c_width, 10):
    board.append(["white" for j in range(0, c_height, 10)])

#board[4][7] = "red"

def pix_to_units(x, y):
    if x > 10 and y > 10:
        i = int(str(x)[:-1])
        j = int(str(y)[:-1])
        return i-1,j-1
    else:
        return 0, 0

def afficher_dessin(): #display board
    for i in range(len(board)):
        b = board[i]
        for j in range(len(b)):
            if b[j] != sdessin["background"]:
                sdessin.create_rectangle(i*10, j*10,i*10+10, j*10+10, fill = b[j], outline = b[j])

def draw():
    afficher_dessin()
    fen.after(200, draw)

def interaction(coords):
    i, j = pix_to_units(coords.x, coords.y)
    board[i][j] = couleur


sdessin.bind("<B1-Motion>", interaction)

sdessin.grid(row =2, column =2, sticky=N)

draw()
fen.mainloop()

Tags: inboardfordefrangeredcoordswidth
1条回答
网友
1楼 · 发布于 2024-09-30 20:22:01

您在每次更新中都创建了新的矩形项,这是CPU高使用率的原因,并且不是必需的。只需在iteraction()函数中创建一次矩形项并更新其颜色,无需使用after()来更新电路板

以下是基于您的简化代码:

from tkinter import Tk, Canvas, NW, NE, N

fen = Tk()
fen.geometry("1380x740")
fen.title("Dessine moi un mouton !")

c_width = 800
c_height = 600
couleur = "red"
epaisseur= 10

sdessin = Canvas(width = c_width, height = c_height, bg ='white')

rows, cols = c_height//10, c_width//10
# create the board
board = [['white' for _ in range(cols)] for _ in range(rows)]
# draw the board
for row in range(rows):
    for col in range(cols):
        x, y = col*10, row*10
        sdessin.create_rectangle(x, y, x+10, y+10, fill=board[row][col], outline='',
                                 tag='%d:%d'%(row,col))  # tag used for updating color later

def pix_to_units(x, y):
    return y//10, x//10   # row, col

def interaction(event):
    row, col = pix_to_units(event.x, event.y)
    board[row][col] = couleur
    tag = '%d:%d' % (row, col)
    sdessin.itemconfig(tag, fill=couleur)

sdessin.bind("<B1-Motion>", interaction)
sdessin.grid(row=2, column=2, sticky=N)

fen.mainloop()

相关问题 更多 >