【问题标题】:How to set a specific function to every widget while using loops in tkinter from Python 3?如何在 Python 3 的 tkinter 中使用循环时为每个小部件设置特定功能?
【发布时间】:2017-11-04 20:21:00
【问题描述】:

我正在从 Python 3 探索 tkinter,但在使用循环创建包含函数的小部件时遇到了问题。我有这个代码:

from tkinter import *

def test(no, button_name, event=None):
    def callback():
        print(button_name)
    return callback

root = Tk()
list_of_buttons = 'Button 1, Button 2, Button 3, Button 4, Button 5'.split(', ')
for no, i in enumerate(list_of_buttons):
    list_of_buttons[no] = Button(root, text=i, command=test(no=no, button_name=i))
    list_of_buttons[no].grid(row=no, column=0)
root.mainloop()

此代码运行良好,结果是当您按下每个按钮时,它会打印出自己的名称。但是,我认为按钮很难看,即使是 ttk,所以我打算制作一些自定义屏幕,用标签和图像代替按钮。然后我尝试将Button小部件更改为Label,以这种方式:

list_of_buttons[no] = Label(root, text=i)
list_of_buttons[no].bind('<Button-1>', test(no=no, button_name=i))

然后出现错误:

TypeError: callback() 接受 0 个位置参数,但给出了 1 个

我厌倦了使用 lambda 进行修复,但是当我使用它时,当我按下标签时它就不起作用了:

list_of_buttons[no].bind('<Button-1>', lambda event: test(no=no, button_name=i))

我也试过这样调用回调函数:

return callback()

但这只会打印“按钮 5”。有没有办法对需要事件绑定的标签做同样的事情?

【问题讨论】:

    标签: python-3.x lambda tkinter mouseevent


    【解决方案1】:

    修改你的回调定义为:

    def callback(event=None):
        print(button_name)
    

    这是因为 tkinter 调用的回调实际上是 callback 函数,而不是 test 函数。测试功能不需要event=None

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多