Python Tkinter lambda增量IntVar on按钮点击
习题集 我想创建一个计数器小部件,可以通过3个操作进行操作:Python Tkinter lambda增量IntVar on按钮点击,python,button,lambda,tkinter,Python,Button,Lambda,Tkinter,习题集 我想创建一个计数器小部件,可以通过3个操作进行操作: 通过编辑tk.Entry小部件中的数据来编辑绑定的tk.Entry Textvariable 通过单击条目右侧的ttk.按钮增加变量 通过单击条目左侧的ttk.按钮减少变量 当前代码 #!/usr/bin/env python2 # -*- encoding: utf-8 -*- import Tkinter as tk import ttk counter=tk.IntVar()
- 通过编辑
tk.Entry小部件中的数据来编辑绑定的
tk.Entry Textvariable
- 通过单击条目右侧的
增加变量ttk.按钮
- 通过单击条目左侧的
减少变量ttk.按钮
#!/usr/bin/env python2
# -*- encoding: utf-8 -*-
import Tkinter as tk
import ttk
counter=tk.IntVar()
def printerCounterWidget(master):
"""
This will specify the appearance of the PrintCounter
"""
#Create the UI
__frame = ttk.Frame(master)
__frame.grid()
global counter
####################################################################
ttk.Button(__frame, text="-", command=lambda: counter.set( counter.get() - 1 ) ).grid(row=0, column=0)
####################################################################
ttk.Entry(__frame, textvariable=counter).grid(row=0, column=1)
####################################################################
ttk.Button(__frame, text="+", command=lambda: counter.set( counter.get() + 1 ) ).grid(row=0, column=2)
####################################################################
if __name__=="__main__":
app=tk.Tk()
ttk.Label(app, text="printerCounterWidget").grid()
printerCounterWidget(app)
app.mainloop()
不幸的是,我没有设法(至少还没有)让lambda表达式工作
我确实知道当前调用永远不会工作,因为它在声明时被调用
有人能告诉我正确设置lambda表达式的方向吗?好的,时间不长。我在兰姆达斯上了冒号后发现了这个问题 counter=tk.IntVar()在全局版本内不起作用。 把它放到函数中解决了它
def printerCounterWidget():
[...]
counter=tk.IntVar() # removed "global counter"
[...]
好的,时间不长。我在兰姆达斯上了冒号后发现了这个问题 counter=tk.IntVar()在全局版本内不起作用。 把它放到函数中解决了它
def printerCounterWidget():
[...]
counter=tk.IntVar() # removed "global counter"
[...]
您缺少一个冒号:
lambda:counter…
完全正确!SRY4那个打字错误!我编辑了这个问题,为什么在这里使用lambda,而不是创建一个合适的函数?lambda使代码更难编写、读取和维护。布莱恩:这个“小部件”应该稍后在TkinterTreectrl视图中使用。对于我来说,我更喜欢lambda而不是基于事件发送者标识的正确回调,因为在树中有超过20000个数据集(行)需要花费太长时间。如果你知道一个合适的解决方案,我将非常感激:-)你缺少一个冒号:lambda:counter…
完全正确!SRY4那个打字错误!我编辑了这个问题,为什么在这里使用lambda,而不是创建一个合适的函数?lambda使代码更难编写、读取和维护。布莱恩:这个“小部件”应该稍后在TkinterTreectrl视图中使用。对于我来说,我更喜欢lambda而不是基于事件发送者标识的正确回调,因为在树中有超过20000个数据集(行)需要花费太长时间。如果您知道一个合适的解决方案,我将非常感激:-)