使用Tkinter Spinbox的输入使用Pyplot绘制图 [英] Plot graph with pyplot using input from tkinter spinbox

查看:71
本文介绍了使用Tkinter Spinbox的输入使用Pyplot绘制图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中工作,该项目需要随着 tkinter spinbox 中的输入更改而动态绘制图形.

I am working in a project which needs to plot a graph dynamically as the inputs in a tkinter spinbox is changed.

我有一个示例代码:

from tkinter import *
from tkinter import font
from tkinter.font import Font
from tkinter import messagebox
print("'Tkinter' module is found as tkinter.")

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
print("Importing matplotlib from libraries.")


master = Tk()

def ok(x_val=1000,y_val=20):
         fig = Figure(figsize=(5,5),dpi=70)
         ax = fig.subplots()
         ax.set_title("Right Ear")
         ax.set_ylabel("db HL")
         ax.set_xlabel("Frequency")
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)
         ax.set_facecolor("#ffd2d2")

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)


         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])


         ax.plot([x_val],[y_val],'r+',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)

def action():
        print(spin.get())
        canvas.draw()
        ok(spin.get(),10)

spin = Spinbox(master, from_=125,to=8000,command=action)
spin.grid(column=5,row=2)

ok()

这段代码并没有改变情节,我无法理解如何改变它,准确地说,如何使用canvas.draw()在这里完成工作.该Spinbox的取值范围是125到8000,我无法弄清楚如何在每次更改Spinbox时取其值(可以使用 command = 但如何实现)并将其提供给xax.plot() 的轴并动态绘制.随着 spinbox 的值发生变化,绘图也会更改到新位置,并从之前的位置移除之前的绘图.

This code does not change the plot, I cannot understand how to change it, to be precise, how to use canvas.draw() here to do the work. The spinbox has value range from 125 to 8000, I could not figure out how to take the value of the spinbox every time it changes (can use command= but how to implement) and feed it to the x axis of ax.plot() and plot dynamically. As the value of spinbox changes the plot also changes to the new position and removes the previous plot from the previous position.

推荐答案

您需要使您需要的变量可用.通常的方法是使用一个类并使这些类变量.然后可以从类内部(self)或外部作为属性访问它们.

You need to make the variables you need available. A usual approach is to use a class and make those class variables. Those can then be accessed from within the class (self) or outside as attributes.

from Tkinter import *

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class PlotClass():
    def __init__(self):
         fig = Figure(figsize=(5,5),dpi=70)
         ax = fig.subplots()
         ax.set_title("Right Ear")
         ax.set_ylabel("db HL")
         ax.set_xlabel("Frequency")
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)
         ax.set_facecolor("#ffd2d2")

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)

         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

         self.line, = ax.plot([],[],'r+',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         self.canvas = canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)
         self.spin = Spinbox(master, from_=125,to=8000,command=self.action)
         self.spin.grid(column=5,row=2)

    def ok(self, x=1000,y=20):
        self.line.set_data([x],[y])
        self.canvas.draw_idle()

    def action(self):
        self.ok(float(self.spin.get()),10)

master = Tk()
plotter = PlotClass()
plotter.ok(125,10)
master.mainloop()

注意:在较新版本的 matplotlib 中,您应该使用 NavigationToolbar2Tk 而不是 NavigationToolbar2TkAgg.

Note: In newer versions of matplotlib you should use NavigationToolbar2Tk instead of NavigationToolbar2TkAgg.

这篇关于使用Tkinter Spinbox的输入使用Pyplot绘制图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆