我正在使用 Tkinter 在 python 中制作 GUI,并且在将许多小部件打包到屏幕上时遇到了一些性能问题,例如打包一个 50x50 的按钮网格需要几秒钟。
似乎是在屏幕上绘制(或排列?)小部件的过程需要时间。我曾尝试同时使用网格和放置几何管理器。
我想知道使用多处理是否可以加快速度?我欢迎任何其他可以显着加快速度的建议。
import Tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
for i in range(50):
for j in range(50):
widget = tk.Frame(frame, bd=2, relief='raised', height=10, width=10)
widget.grid(row=i, column=j) # using place is barely quicker
tk.Button(root, text='pack', command=frame.pack).pack()
root.mainloop()
最佳答案
正如评论中所建议的,最好的解决方案最终是使用 Canvas 并在其上绘制,而不是打包这么多小部件,这似乎对其速度有绝对限制。
我通过有效地截取屏幕截图来使用内置按钮来创建未单击和单击状态的图像。假设图像文件存储为 im_up.png
和 im_down.png
,那么下面的代码说明了 Canvas 解决方案。
import Tkinter as tk
# Uses Python Imaging Library.
from PIL import Image as ImagePIL, ImageTk
root = tk.Tk()
canvas = tk.Canvas(root, height=500, width=500, highlightthickness=0)
canvas.pack()
images = dict()
for name in ['up', 'down']:
im = ImagePIL.open('im_{}.png'.format(name))
# Resize the image to 10 pixels square.
im = im.resize((10, 10), ImagePIL.ANTIALIAS)
images[name] = ImageTk.PhotoImage(im, name=name)
def set_cell_image(coord, image):
# Get position of centre of cell.
x, y = ((p + 0.5) * 10 for p in coord)
canvas.create_image(x, y, image=image)
for i in range(50):
for j in range(50):
set_cell_image((i, j), images['up'])
def click(event):
coord = tuple(getattr(event, p)/10 for p in ['x', 'y'])
set_cell_image(coord, images['down'])
canvas.bind('<Button-1>', click)
root.mainloop()
关于python - 打包许多小部件时的 Tkinter 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312592/