繁体   English   中英

如何使用来自 tkinter 文本小部件的输入创建 matplotlib 饼图?

[英]How to create a matplotlib pie chart with input from a tkinter text widget?

我想要一个带有 tkinter 文本小部件的 GUI,用户可以在其中输入值。 点击“创建”后。 按钮 我希望程序打开一个新的 window 并使用输入的值创建一个 matplotlib 饼图。 我试图get输入并将其存储在一个变量中,以便程序使用它来创建饼图。 但这显然不起作用。

据我所知,到目前为止,我宁愿使用一个数组来让它工作,但是:

  1. 我不知道如何将输入保存为数组以供饼图使用。
  2. 我不知道必须以哪种方式将输入写入文本小部件才能创建数组。 对于条目小部件,可以使用split来指定单个值用逗号、空格等分隔...但我还没有找到与文本小部件类似的东西。
import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def open_pie_chart():
    inputVariable = input_text.get("1.0","end-1c")
    pie_chart_window = tk.Tk()
    frame_pie_chart = tk.Frame(pie_chart_window)
    frame_pie_chart.pack()
    vehicles = ['car', 'bus', 'bicycle', 'motorcycle', 'taxi', 'train']
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    ax.pie(inputVariable, radius=1, labels=vehicles)
    chart1 = FigureCanvasTkAgg(fig,frame_pie_chart)
    chart1.get_tk_widget().pack()

root = tk.Tk()

input_frame = tk.LabelFrame(root, text="Input")
input_text = tk.Text(input_frame)

create_button = tk.Button(root, command=open_pie_chart, text="Create!")

input_frame.grid(row=1, column=0)
input_text.grid(row=1, column=0)
create_button.grid(row=2, column=0)

root.mainloop()

您非常接近,我不确定您在哪里绊倒,因为在您的问题中您知道正确的答案(使用split() )。 您所要做的就是设置一个您希望用户用于输入的格式(也许只是用逗号分隔它们的值,这就是我在这个例子中使用的),然后在那个分隔符上分割它们。 如果您只想要空格,那么您只需要.split()而不是我在示例中使用的.split(',') 然后,将这些值转换为int并保存新的inputVariable

import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = tk.Tk()

def open_pie_chart():
    inputVariable = input_text.get(1.0, "end-1c")
    inputVariable = [int(x) for x in inputVariable.split(',')]
    pie_chart_window = tk.Tk()
    frame_pie_chart = tk.Frame(pie_chart_window)
    frame_pie_chart.pack()
    vehicles = ['car', 'bus', 'bicycle', 'motorcycle', 'taxi', 'train']
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    ax.pie(inputVariable, radius=1, labels=vehicles)
    chart1 = FigureCanvasTkAgg(fig,frame_pie_chart)
    chart1.get_tk_widget().pack()
    
input_frame = tk.LabelFrame(root, text="Input, (format = #, #, #, #, #, #)")
input_text = tk.Text(input_frame)

create_button = tk.Button(root, command=open_pie_chart, text="Create!")

input_frame.grid(row=1, column=0)
input_text.grid(row=1, column=0)
create_button.grid(row=2, column=0)

root.mainloop()

Output: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM