tkinter 与 matplotlib [英] tkinter with matplotlib

查看:31
本文介绍了tkinter 与 matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到可以在 tkinter 中嵌入 pyplot,但我遇到了问题:

I read it is possible to embed a pyplot in tkinter, but I'm having a problem:

我需要显示一些框架,其中在 Tkinter 主窗口的框架中显示一个 pyplot,并且它必须对我的按键做出反应.

I need to display some frames, among which a pyplot in a frame of the main Tkinter window, and it has to react to my keypresses.

根据http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html这有效:

#!/usr/bin/env python
from Tkinter import *
import matplotlib
matplotlib.use('TkAgg')    
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.backend_bases       
from matplotlib.figure import Figure    
import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.wm_title("Embedding in TK")


f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

a.plot(t,s)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def on_key_event(event):
    print('you pressed %s'%event.key)

canvas.mpl_connect('key_press_event', on_key_event)

def _quit():
    root.quit()     # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)

Tk.mainloop()

我很高兴...但如果我尝试,例如,在其顶部放置一个文本框:

And I was happy... but if I try, as an example, to have a Text frame on top of it:

t=Text(root)
t.pack()

(在画布变量定义之前)只要我点击文本框 &写进去,没有办法点击pyplot窗口,让它再次抓住我的按键!

(before the canvas variable definition) as soon as I click on the Text frame & write into it, there is no way to click on the pyplot window and make it catch my keypresses again!

有什么提示吗?

推荐答案

在 tkinter 中,关键事件被路由到获得焦点的小部件,因此您的问题是将焦点设置回画布.这可以通过绑定点击画布来设置焦点.

In tkinter, key events are routed to the widget that get the focus, thus your problem is to set focus back to the canvas. This is possible through binding on click on canvas to set the focus.

例如:

canvas.mpl_connect('button_press_event', lambda event:canvas._tkcanvas.focus_set())
#or canvas._tkcanvas.bind('<Button1>', ...)

这篇关于tkinter 与 matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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