【问题标题】:Pyplot interactive mode blocks Tkinter RadioButtonPyplot 交互模式块 Tkinter RadioButton
【发布时间】:2017-06-04 04:26:43
【问题描述】:

我正在尝试在应用程序中结合 pyplot 和 Tkinter。在这个应用程序中,用户可能首先创建一个图形,然后打开一个 GUI。现在我发现在打开GUI之前创建图形时,GUI的Radiobutton只返回一个空变量(在我的例子中是一个空字符串),没有分配正确的值。在制作 GUI 之前没有创建图形时,单选按钮可以正常工作。

最小的失败示例:

from matplotlib import pyplot as plt
import Tkinter as tk

class GUI(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.shape = tk.StringVar()
        self.circleButton = tk.Radiobutton(self, text="Circle", variable=self.shape, value='circle', command=self.selected)
        self.circleButton.pack()

    def selected(self):
        print self.shape.get()

if __name__ == "__main__":
    plt.ion()
    plt.figure()
    gui=GUI()
    gui.mainloop()

运行此代码时,单击单选按钮会打印一个空字符串,而不是“圆圈”。如果我删除 plt.figure(),单击按钮会打印“圆圈”(如预期的那样)。

谁能告诉我如何解决这个问题,并允许用户先制作一个图形然后打开 GUI?

【问题讨论】:

  • matplot 可以运行自己的 mainloop 并且 tkinter 可能只使用一个 mainloop 才能正常工作。 matplot 具有与 Tkinter 配合使用的特殊功能 - 查找文档或教程“如何在 tkinter 窗口中嵌入绘图”

标签: python matplotlib tkinter


【解决方案1】:

matplot 可以使用tkinter 来创建自己的窗口并运行自己的mainloop,而tkinter 只能使用一个mainloop 和一个Tk 窗口才能正常工作。

tkinterToplevel 来创建第二/第三个窗口,所以你可以尝试使用它

from matplotlib import pyplot as plt
import Tkinter as tk

class GUI(tk.Toplevel):

    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.shape = tk.StringVar()
        self.circleButton = tk.Radiobutton(self, text="Circle", variable=self.shape, value='circle', command=self.selected)
        self.circleButton.pack()

    def selected(self):
        print(self.shape.get())

plt.ion()
plt.figure()
GUI().mainloop()

顺便说一句:matplot 具有与 Tkinter 配合使用的特殊功能 - 查找有关 "how to embed matplotlib in Tkinter window" 的文档或教程

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2013-05-22
    • 2014-08-12
    • 2017-01-06
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    相关资源
    最近更新 更多