【问题标题】:Drawing a selection area with mouse in Tkinter在 Tkinter 中用鼠标绘制选择区域
【发布时间】:2014-09-04 18:36:24
【问题描述】:

我正在开发一个应用程序,它以.csv 形式从用户那里获取输入,并使用matplotlib 绘制相应值的图形。

def plotgraph():
    x = []
    y = []
    data = text.get("1.0", END)
    sepFile = data.split('\n')

    for plotPair in sepFile:
        xAndY = plotPair.split(',')
        if len(xAndY[0]) != 0 and len(xAndY[1]) != 0:
            x.append(float(xAndY[0]))
            y.append(float(xAndY[1]))

    graph = Figure(figsize=(5,4), dpi=100)
    a = graph.add_subplot(111)
    a.plot(x,y)
    a.set_xlabel('Velocity')
    a.set_ylabel('Absorbance')
    canvas = FigureCanvasTkAgg(graph, master=RightFrame)
    canvas.show()
    canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))

我想要在Tkinter 中使用类似Matplotlib: draw a selection area in the shape of a rectangle with the mouse 的函数,它在选择后给了我x0, x1, y0, y1。我可以根据我的需要使已经提出的问题发挥作用并对其进行自定义,但不知道我在 __init__(self) 中犯了什么错误

root = Tk()
class Annotate(object):
    def __init__(self):
        self.fig = mplfig.Figure(figsize=(1.5, 1.5))
        self.ax = self.fig.add_subplot(111)
        self.ax.plot([0,1,2,3,4],[0,8,9,5,3])        
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=root)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

当我运行这段代码时,我得到一个空白的 Tk 窗口。谁能告诉我我应该做什么以及我在做什么错误

【问题讨论】:

  • 你是在控制台/终端/cmd.exe 中运行的吗?也许有一些错误信息。如果是,则添加有问题的完整错误消息。
  • 您是否仅使用root=Tk()class Annotate(object) 运行了这部分代码?如果是,那么你只运行root=Tk(),你必须学习如何使用类。
  • 你的错误:你没有使用类Annotate创建对象,所以python不能在__init__中运行代码。
  • @furas 我在 Spyder(它有一个控制台)中运行我的代码。我正在尝试与您的建议合作,看看事情是否成功。感谢您的建议。

标签: python matplotlib tkinter


【解决方案1】:

要使用你需要的类,列出类似这样的东西

class Annotate(object):
    def __init__(self):
        print "Annotate is runing"
        # rest of your code

root = Tk()
my_object = Annotate()

root.mainloop()

你可能需要更多的工作来解决这个问题。

【讨论】:

  • 感谢您的回答。我没有创建任何对象。现在初始和最终坐标显示在控制台中,但选择区域没有显示..你能看看这个stackoverflow.com/q/24748589/1581133
猜你喜欢
  • 2012-08-16
  • 2017-05-22
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 2016-10-14
  • 2014-07-30
相关资源
最近更新 更多