Pyplot交互模式阻止Tkinter RadioButton

时间:2017-01-19 12:57:28

标签: python matplotlib tkinter

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

最小失败的例子:

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()

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

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

1 个答案:

答案 0 :(得分:0)

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()

BTW:matplot具有与Tkinter一起使用的特殊功能 - 查找有关"how to embed matplotlib in Tkinter window"的文档或教程