【问题标题】:How to make a Button()s state continuous?如何使 Button()s 状态连续?
【发布时间】:2021-07-17 14:33:35
【问题描述】:

我在网格中有一个 for 循环启动按钮,我希望按钮状态可以切换,而不是在不再按住鼠标按钮时关闭。我还需要知道哪个按钮调用了按钮的功能,因为我在同一个 for 循环中初始化了其中的一些,这意味着一旦激活它们都会调用相同的功能,有人知道如何帮助我吗?

编辑:

最小的工作示例:

import tkinter as gui

def createWindow():
    window = gui.Tk()
    window.title("GoL")
    icon = gui.PhotoImage(file='Not showing ya\'ll my files.png')
    window.iconphoto(True, icon)
    window.config(background="black")
    label = gui.Label(window,\
        text="Generation:",\
        bg="black",\
        fg="white",\
        font=("Consolas",20))
    label.pack()
    return window

def newBoard(x = 10,y = 10):
    window = createWindow()
    for i in range(0, y):
            for j in range(1, x+1):
                button = gui.Button(window,bg="black",height=1,width=2,command=changeState)
            button.place(x=23*(j-1),y=23*(i+2))
    window.mainloop()

我想要的是函数changeState来改变

【问题讨论】:

  • 您能否提供一个最小的工作示例,说明您尝试了什么以及您需要什么?还可以使用lambda 传递按钮的标识符。您是否将按钮放在列表中?
  • 您可能想研究 Radiobuttons 和 indicatoron 选项。

标签: python tkinter button


【解决方案1】:

您可以通过保留按钮列表 (buttons) 来实现此目的,然后使用 lambda 函数将行/列号传递给按钮命令函数,然后您可以更改所选按钮的属性。在这种情况下,它会在黑色和白色背景颜色之间切换。

def changeState(i, j):
    global buttons
    b = buttons[i][j]
    b.config(bg = "white") if b.cget("bg") != "white" else b.config(bg = "black")

def newBoard(x = 10,y = 10):
    global buttons
    window = createWindow()
    buttons = []
    for i in range(0, y):
        row = []
        for j in range(1, x+1):
            button = gui.Button(window,bg="black",height=1,width=2,command=lambda i=i, j=j-1: changeState(i,j))
            row.append(button)
            button.place(x=23*(j-1),y=23*(i+2))
        buttons.append(row)
    window.mainloop()

【讨论】:

  • 我已经解决了这个问题,但是当我达到你在这里提出的完全相同的解决方案时,我仍然会接受它
猜你喜欢
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 2021-06-11
  • 2010-12-24
  • 1970-01-01
  • 2020-12-17
相关资源
最近更新 更多