python - 打包许多小部件时的 Tkinter 性能

标签 python python-2.7 user-interface tkinter

我正在使用 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.pngim_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/

相关文章:

python - 如何实现具有不同参数类型的Python函数

python - pip 损坏,重新安装不起作用。 EC2

user-interface - 哪些语言具有良好的 GUI API/Designer?

python - 图像上的Canny操作

Python 3 中的 Python 2 打印功能

user-interface - 交互设计、视觉设计、网页设计、UX 设计、UI 设计、UI 开发之间有什么区别?

R- spplot 不在 gWidgets GUI 中绘制栅格堆栈

python - 将 HTML 解析为纯文本

Python Tkinter 计算器不会计算输入小部件中的文本

python - 如何使用 "contains"进行过滤?