环境:Ubuntu14、Python3.4、Pycharm2018
一、使用command=lambda: 的形式传参
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from tkinter import * import tkinter.messagebox as messagebox def createpage(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 ) def btn_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()和Entry textvariable对参数进行绑定
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from tkinter import * import tkinter.messagebox as messagebox class A: """ 使用StringVar() 和 textvariable 对Button进行绑定 实现Button对数据进行操作 解决Button传参问题 StringVar()的数需要使用.get()获取值 """ def __init__( self , master): self .root = Frame(master) self .num1 = StringVar() # 第一个数字 self .num2 = StringVar() # 第一个数字 self .createpage() def createpage( 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 ) def btn_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进行数据事件处理,方法一为Button command下传递参数,方法二为控件下使用textvariable对StringVar的参数进行绑定。(我比较推荐使用方法二)。好了,今天就说到这吧,希望大家多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/181932/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)