关于Python Tkinter Button控件command传参问题的解决方式
环境:Ubuntu14、Python3.4、Pycharm2018
一、使用command=lambda:的形式传参
代码如下
fromtkinterimport* importtkinter.messageboxasmessagebox defcreatepage(master): master=Frame(root) master.pack() Label(master,text='num1').grid(row=0,column=0,stick=W,pady=10) e1=Entry(master) e1.grid(row=0,column=1,stick=E) Label(master,text='num2').grid(row=1,column=0,stick=W,pady=10) e2=Entry(master) e2.grid(row=1,column=1,stick=E) #Button传递参数 Button( master,text='加',command=lambda:btn_def(e1.get(),e2.get()) ).grid(row=2,column=0,stick=W) Button(master,text='减').grid(row=2,column=1,stick=E) Label(master,text='说明').grid(row=3,column=0,stick=W,pady=10) Label(master,text='只写了加法(请输入简单数字测试button传参)').grid( row=3,column=1,stick=E ) defbtn_def(num1,num2): num=int(num1)+int(num2) messagebox.showinfo('结果','%d'%num) if__name__=='__main__': root=Tk() root.title('Demo') root.geometry('400x150') createpage(root) root.mainloop()
二、使用StringVar()和Entrytextvariable对参数进行绑定
代码如下
fromtkinterimport* importtkinter.messageboxasmessagebox classA: """ 使用StringVar()和textvariable 对Button进行绑定 实现Button对数据进行操作 解决Button传参问题 StringVar()的数需要使用.get()获取值 """ def__init__(self,master): self.root=Frame(master) self.num1=StringVar()#第一个数字 self.num2=StringVar()#第一个数字 self.createpage() defcreatepage(self): self.root.pack() Label(self.root,text='num1').grid(row=0,column=0,stick=W,pady=10) #textvariable和StringVar的num1绑定 Entry(self.root,textvariable=self.num1).grid(row=0,column=1,stick=E) Label(self.root,text='num2').grid(row=1,column=0,stick=W,pady=10) #textvariable和StringVar的num2绑定 Entry(self.root,textvariable=self.num2).grid(row=1,column=1,stick=E) #Button传递参数 Button( self.root,text='加',command=self.btn_def ).grid(row=2,column=0,stick=W) Button(self.root,text='减').grid(row=2,column=1,stick=E) Label(self.root,text='说明').grid(row=3,column=0,stick=W,pady=10) Label(self.root,text='只写了加法(请输入简单数字测试button传参)').grid( row=3,column=1,stick=E ) defbtn_def(self): #使用.get()获取值 num=int(self.num1.get())+int(self.num2.get()) messagebox.showinfo('结果','%d'%num) if__name__=='__main__': root=Tk() root.title('Demo2') root.geometry('400x150') A(root) root.mainloop()
三、总结
以上两种方式都是使用了Button进行数据事件处理,方法一为Buttoncommand下传递参数,方法二为控件下使用textvariable对StringVar的参数进行绑定。(我比较推荐使用方法二)。好了,今天就说到这吧,希望大家多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。