python - 如何配置已在该按钮上使用参数的功能中单击的按钮?
问题描述
我需要能够配置在函数内单击的按钮,同时将函数用于多个按钮
我见过人们使用参数来调用函数中按钮的名称,但是我已经将参数用于我的代码的必要部分,所以我无法做到这一点
clicked = 0
def click_place(position):
while clicked < 6:
clicked += 1
place_positions.append(position)
.config(bg="yellow") #where I need help
#placement buttons
place_buttons = Frame(window)
place_positions = []
but1 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A1'))
but1.grid(row = 0, column = 0)
but2 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A2'))
but2.grid(row = 0, column = 2)
place_buttons.place(x=250, y=500, anchor=CENTER)
解决方案
最简单的方法是使用'A1'
和'A2'
作为键将按钮存储在字典中
buttons = {
'A1': but1,
'A2': but2,
}
然后,鉴于position
将设置为'A1'
or ,您可以使用'A2'
引用按钮。position
buttons[position]
另一种解决方案是将按钮作为参数传递:
def click_place(position, button):
...
...
but1 = Button(place_buttons, height = 2, width = 5)
but1.configure(command= lambda:click_place('A1', but1))
...
推荐阅读
- php - 用于匹配多行 PHPDoc 注释的正则表达式
- javascript - 找不到 babel-loader。突然出现这个错误。请问有人有办法解决吗?
- python - PocketSphinx 音频设备列表
- php - 我正在尝试将百分比设置为新变量的结果,但出现错误
- swift - 连接到已完成的发布者时,接收器未接收到值
- algorithm - 分布式/内存绑定的云点注册算法
- java - 不满足条件时抛出异常的注解
- php - PHP Godot 集成
- reactjs - React Native Stack Navigator 在背面保持状态
- c++ - 不断收到此错误:无法从 'int' 转换为 'std::__cxx11::string' {aka 'std::__cxx11::basic_string
'}|