单击时更改按钮外观

时间:2016-12-29 21:04:27

标签: python button tkinter

在我的GUI应用程序中,我为给定列表中的每个项目创建一个按钮。当按下按钮时,所述按钮的背景变为绿色,并且显示为"凹陷"。其他按钮显示为凸起并具有默认颜色。我的问题是只有最后创建的按钮才会改变颜色和外观。我相信这是因为它包含回调函数。

我希望在按下初始按钮后,当用户按下不同的按钮时,新按钮变为绿色并且显示为凹陷,并且前一个按钮变为凸起和默认颜色。我的猜测是我需要创建一个包含所有已创建按钮的列表,并在回调函数中为其应用逻辑以实现我想要的行为。但是如何呢?

possible_loots = {
  'shitty' => ['Worn Dagger', 'Dirty Panties', 'Broken Staff', 'Bear Claw', 'Used Bandage'],
  'decent' => ['Simple Staff', 'Alchemy Bag', 'Mask of Emptiness', 'Cloak of Disappearance', 'Large Health Potion'],
  'epic' => ['Sword of 1000 Truths', 'The Master Sword', 'BFG', 'The Fate of the World', 'Infinite Bag of Infinity']
} 

adjective = case cr
when (0..3) then 'shitty'
when (4..8) then 'decent'
when (9..10) then 'epic'
end

loot = (1..3).map{ possible_loots[adjective].sample}.join(', ')
puts "Your loot is #{loot}. Grats on the #{adjective} loot!"

# cr = 5
#=> Your loot is Cloak of Disappearance, Simple Staff, Alchemy Bag. Grats on the decent loot!
# cr = 10
#=> Your loot is Infinite Bag of Infinity, BFG, The Master Sword. Grats on the epic loot!

2 个答案:

答案 0 :(得分:2)

在Stackoverflow上这么多次,所以我不知道是否应该再写一次。

Buttoncommand=分配函数但它可以不带参数赋值函数。如果您需要参数,则必须使用lambda。我参考按钮分配功能,所以功能可以使用正确的按钮并更改它。

需要lambdafor-loop的{​​{1}}中的

arg=btn因为直接select_button(arg)将在所有功能中使用最后一个按钮。

至于将上一个按钮更改为原始颜色,您可以使用变量记住当前点击的按钮,然后您可以轻松更改颜色。

问题可能是找到按钮的原始颜色,所以我从新点击的按钮复制它。

select_button(btn)

编辑:你也可以使用import tkinter as tk # --- functions --- def select_button(widget): global previously_clicked if previously_clicked: previously_clicked['bg'] = widget['bg'] previously_clicked['activebackground'] = widget['activebackground'] previously_clicked['relief'] = widget['relief'] widget['bg'] = 'green' widget['activebackground'] = 'green' widget['relief'] = 'sunken' previously_clicked = widget # --- main --- names = ['Button A', 'Button B', 'Button C'] root = tk.Tk() previously_clicked = None for i, name in enumerate(names, 2): btn = tk.Button(root, text=name) btn.config(command=lambda arg=btn:select_button(arg)) #btn['command'] = lambda arg=btn:select_button(arg) btn.grid(row=i, column=0, sticky='w') root.mainloop() 一些选项来做同样的事情 - 而且没有功能:

请参阅:http://effbot.org/tkinterbook/radiobutton.htm

Radiobutton

答案 1 :(得分:0)

我遇到了类似的问题,最终在函数中定义了一个函数来解决我的问题。在你的情况下,我们会得到这个:

  cars: {
    ids: [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9
    ],
    entities: {
      '1': {
        id: 1,
        name: 'car A',
        options: [
          {
            id: 1,
            name: 'hybrid',
            like: false
          },
          {...}

这里的重要部分是,我们通过定义一个直接集成这些参数的函数来绕过无法将参数传递给 button['command'] 的困难。

相关问题