Fiv*_*ver 8 python macos tkinter osx-mavericks
我创建了一个简单的应用程序,使用Tkinter的Canvas小部件显示数据的散点图(参见下面的简单示例).绘制10,000个数据点后,应用程序变得非常迟缓,可以通过尝试更改窗口大小来看到.
我意识到添加到Canvas的每个项目都是一个对象,因此在某些时候可能会出现一些性能问题,但是,我预计该级别会远高于10,000个简单的椭圆形对象.此外,我可以在绘制点或与它们交互时接受一些延迟,但在绘制它们之后,为什么只是调整窗口的大小这么慢?
在阅读了使用Canvas小部件的effbot性能问题之后,似乎在调整大小期间可能会有一些不需要的连续空闲任务需要忽略:
Canvas小部件实现了直接的损坏/修复显示模型.对画布的更改以及Expose等外部事件都被视为对屏幕的"损坏".小部件维护一个脏矩形以跟踪受损区域.
当第一个损坏事件到来时,画布会注册一个空闲任务(使用after_idle),当程序返回到Tkinter主循环时,该任务用于"修复"画布.您可以通过调用update_idletasks方法强制更新.
因此,问题是,update_idletasks一旦数据被绘制,是否有任何方法可以使应用程序更具响应性?如果是这样,怎么样?
以下是最简单的工作示例.在加载后尝试调整窗口大小以查看应用程序变得多么迟钝.
我最初在Mac OS X(Mavericks)中观察到了这个问题,当我调整窗口大小时,我的CPU使用量大幅增加.由Ramchandra的评论提示我在Ubuntu中测试了这个,但这似乎没有发生.也许这是一个Mac Python/Tk问题?不会是我遇到的第一个,请看我的另一个问题:
有人也可以在Windows中尝试(我无法访问Windows框)?
我可以尝试使用我自己编译的Python版本在Mac上运行,看看问题是否仍然存在.
最小的工作示例:
import Tkinter
import random
LABEL_FONT = ('Arial', 16)
class Application(Tkinter.Frame):
def __init__(self, master, width, height):
Tkinter.Frame.__init__(self, master)
self.master.minsize(width=width, height=height)
self.master.config()
self.pack(
anchor=Tkinter.NW,
fill=Tkinter.NONE,
expand=Tkinter.FALSE
)
self.main_frame = Tkinter.Frame(self.master)
self.main_frame.pack(
anchor=Tkinter.NW,
fill=Tkinter.NONE,
expand=Tkinter.FALSE
)
self.plot = Tkinter.Canvas(
self.main_frame,
relief=Tkinter.RAISED,
width=512,
height=512,
borderwidth=1
)
self.plot.pack(
anchor=Tkinter.NW,
fill=Tkinter.NONE,
expand=Tkinter.FALSE
)
self.radius = 2
self._draw_plot()
def _draw_plot(self):
# Axes lines
self.plot.create_line(75, 425, 425, 425, width=2)
self.plot.create_line(75, 425, 75, 75, width=2)
# Axes labels
for i in range(11):
x = 75 + i*35
y = x
self.plot.create_line(x, 425, x, 430, width=2)
self.plot.create_line(75, y, 70, y, width=2)
self.plot.create_text(
x, 430,
text='{}'.format((10*i)),
anchor=Tkinter.N,
font=LABEL_FONT
)
self.plot.create_text(
65, y,
text='{}'.format((10*(10-i))),
anchor=Tkinter.E,
font=LABEL_FONT
)
# Plot lots of points
for i in range(0, 10000):
x = round(random.random()*100.0, 1)
y = round(random.random()*100.0, 1)
# use floats to prevent flooring
px = 75 + (x * (350.0/100.0))
py = 425 - (y * (350.0/100.0))
self.plot.create_oval(
px - self.radius,
py - self.radius,
px + self.radius,
py + self.radius,
width=1,
outline='DarkSlateBlue',
fill='SteelBlue'
)
root = Tkinter.Tk()
root.title('Simple Plot')
w = 512 + 12
h = 512 + 12
app = Application(root, width=w, height=h)
app.mainloop()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4843 次 |
| 最近记录: |