我已经在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()
您在每次更新中都创建了新的矩形项,这是CPU高使用率的原因,并且不是必需的。只需在
iteraction()
函数中创建一次矩形项并更新其颜色,无需使用after()
来更新电路板以下是基于您的简化代码:
相关问题 更多 >
编程相关推荐