单个按钮 tkinter 的多个操作 [英] Multiple operations from a single button tkinter

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

问题描述

我一直在使用 matplotlib 和 tkinter 为基于 GUI 的绘图仪编写程序.我为某些选项添加了一个顶级窗口.我想执行一个函数并在单击一个按钮后退出顶层窗口.这可能吗?

I have been writing a program for a GUI based plotter using matplotlib and tkinter. I have added a toplevel window for some options. I want to execute a function and quit the toplevel window after clicking a button. Is that possible?

我面临的问题是我使用了一个必须从主窗口调用的顶级窗口.所以我定义了一个包含这个顶级窗口的函数.如果我定义了另一个可以执行多项操作的函数,它就无法识别顶级窗口.我可以在一个类下定义它,但不确定它是否有效.这是我的代码的一部分,其中包含顶层窗口.

The problem that I face is that I have used a toplevel window which has to be called from the main window. SO I defined a function that contains this toplevel window. If I define another function that can do multiple operations, it cannot recognize the toplevel window. I could define it all under a class but am unsure if it works. Here's a part of my code that contains the toplevel window.

def plt_options(arg):
    global lg_var,col_var,line_type_var,marker_var

    plt_opt = Toplevel(app)

    lg_var = StringVar(None)
    lg_text = Label(plt_opt,text='Legend').grid(row=0,column=0,sticky=E)
    lg_box = Entry(plt_opt,textvar=lg_var)
    lg_box.grid(row=0,column=1,sticky=W)

    col_var = StringVar(None)
    col_var.set('blue')
    col_text = Label(plt_opt,text='Color').grid(row=1,column=0)
    col_chooser = OptionMenu(plt_opt,col_var,'blue','green','red','cyan',\
           'magneta','yellow','black','white')
    col_chooser.grid(row=1,column=1)

    line_type_var = StringVar(None)
    line_type_var.set('Solid')
    line_type_text = Label(plt_opt,text='Line type').grid(row=2,column=0)
    line_chooser = OptionMenu(plt_opt,line_type_var,'Solid','Dashed',\
                          'Dotted','Dash-Dotted','None')
    line_chooser.grid(row=2,column=1)

    marker_var = StringVar(None)
    marker_var.set('None')
    marker_text = Label(plt_opt,text='Marker').grid(row=3,column=0)
    marker_chooser = OptionMenu(plt_opt,marker_var,'Plus','Dot','Circle',\
        'Star','Pentagon','Square','Cross','Diamond','Hexagon','Triangle')
    marker_chooser.grid(row=3,column=1)    

    ok_btn = Button(plt_opt,text='OK',command=testing).grid()

推荐答案

按钮正是为此而设计的.通常你会定义一个函数或方法来做任何你想做的事,然后将该方法分配给按钮的 command 属性:

Buttons are designed for exactly this. Typically you would define a function or method that does whatever you want, then assign that method to the command attribute of the button:

import Tkinter as tk
import tkMessageBox

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        button = tk.Button(text="Press me!", command=self.on_button)
        button.pack()
    def on_button(self):
        tkMessageBox.showinfo(message="Good-bye!")
        self.destroy()

app = SampleApp()
app.mainloop()

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

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