我正在使用tkinter和matplotlib编写脚本进行数据处理,代码的某些部分需要使用多边形选择器来选择感兴趣的区域。但是,PolygonSelector无法检测光标的运动。
应该注意的是,当打开matplotlib图形互动模式时,会发生此问题。
简化的代码和结果如下所示:
private static List<Member>
convertToFlatList(List<Member> memberList, List<Member> flatList)
{
for (Member member : memberList)
{
// Always add the member to flatList
flatList.add(memeber);
// If it has children, add them toore
if (member.getChildren() != null)
{
convertToFlatList(member.getChildren(), flatList);
}
}
return flatList;
}
这是在tkinter GUI上单击“绘制”按钮后的绘图,多边形的起点卡在(0,0),预计将随着光标移动:
当我在tkinter之外致电#!/usr/bin/env python3
import matplotlib
matplotlib.use("TkAgg")
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
root = tk.Tk()
def draw():
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion() # interactive mode is on
plt.show()
def onselect(data_input):
print(data_input)
PS = PolygonSelector(ax, onselect)
tk.Button(root, text='draw', command=draw).pack()
root.mainloop()
时,PolygonSelector可以正常工作:
draw()
答案 0 :(得分:1)
简单的解决方案是确保将多边形选择器设为全局变量。这将使选择器保持可视化更新。
#!/usr/bin/env python3
import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
matplotlib.use("TkAgg")
root = tk.Tk()
ps = None
def draw():
global ps
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
plt.show()
ps = PolygonSelector(ax, on_select)
def on_select(data_input):
print(data_input)
tk.Button(root, text='draw', command=draw).pack()
root.mainloop()
如果将其构建到类中,则可以通过将Polygon Selector用作类属性来避免使用global并获得所需的行为。
#!/usr/bin/env python3
import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
matplotlib.use("TkAgg")
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.ps = None
tk.Button(self, text='draw', command=self.draw).pack()
def draw(self):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
plt.show()
self.ps = PolygonSelector(ax, self.on_select)
def on_select(self, data_input):
print(data_input)
if __name__ == "__main__":
GUI().mainloop()
结果: