【问题标题】:cycling through a list when an event occurs and displaying it on the screen事件发生时循环浏览列表并将其显示在屏幕上
【发布时间】:2018-06-17 09:50:10
【问题描述】:

我正在创建一个数独游戏,并且我生成了一系列按钮来创建一个 9x9 网格。每次单击按钮时,我希望它循环显示数字 1-9 的列表(因此,如果我希望按钮读取 6,则需要单击该按钮 6 次)。我已经设法实现了这一点,但是当我将它带到包含网格的主代码中时,它不起作用。

#Create a 9x9 (rows x columns) grid of buttons inside the frame
for row_index in range(9):
    for col_index in range(9):
        if (row_index in {0, 1, 2, 6, 7, 8} and col_index in {3, 4, 5}) or \
                (row_index in {3, 4, 5} and col_index in {0, 1, 2, 6, 7, 8}): #Colours a group of 3x3 buttons together to differentiate the board better.
            colour = 'gray85'
        else:
            colour = 'snow'
        x = random.randint(1,9)
        btn = Button(frame, width = 12, height = 6, bg=colour) #create a button inside frame 
        btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)

def LeftClick(event, btn):
    global position
    btn.config(text=list1[position])
    position=position+1
    if position == len(list1):
        position=0

btn.bind("<Button-1>", LeftClick)

知道为什么这不起作用吗?目前,当我单击按钮时没有任何反应。

【问题讨论】:

  • 我不明白你的意思 - 我已经包含了我的示例代码。
  • 复制/粘贴你的样本有什么作用吗?
  • 不,样本没有任何作用——我说过。单击按钮时,它保持空白。不幸的是,我无法显示实际结果,因为我没有 gyazo 或类似的东西,并且无法在此处打印打印屏幕。对不起
  • 抱歉,如果你没时间看minimal reproducible example,我没时间帮忙。
  • @JamesAnderson 示例做了某事,它引发了异常。

标签: python events button tkinter sudoku


【解决方案1】:

您需要通过向其添加print('click') 测试消息来确保调用LeftClick()。您还需要将功能绑定到按钮。在你的 for 循环中添加这个:

btn.bind("<Button-1>", LeftClick)

LeftClick()函数需要更新如下:

def LeftClick(event):
    next_value = " 123456789 "

    try:
        current_value = next_value[next_value.index(str(int(event.widget['text']))) + 1]
    except ValueError:
        current_value = "1"

    event.widget.config(text=current_value)

这会读取按钮中的当前文本并从next_value 中选择要使用的下一个值。这包括一个允许您取消选择单元格的空间。所以一开始它会失败并被赋予1的起始值。下一次单击它将读取1,将其转换为整数并在next_value 中找到值的索引。然后它会在下一个索引处选择值。


要编码New Game 按钮,您需要一次更改每个按钮上的文本,目前您只执行最后创建的按钮。为此,您需要保留对您创建的所有按钮的引用。目前代码用下一个覆盖每个按钮变量。在代码顶部添加一个空按钮列表:

buttons = []

在绑定下的for 循环中的下一步:

buttons.append(btn)    

那么你的Clear()函数可以如下:

def Clear(): 
    for btn in buttons:
        btn.config(text=" ") 

【讨论】:

  • 我已经实现并尝试过了,但它仍然没有在我的按钮网格上显示任何数字。
  • 函数被调用了吗?添加print() 语句对其进行测试。
  • 它应该被调用 - 我已经将按钮点击与函数同步
  • btn.bind("", LeftClick) 我的代码上有这个
  • 更正 - 我在函数中添加了打印,但没有任何输出。任何想法为什么??
猜你喜欢
  • 2019-08-08
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2017-05-06
相关资源
最近更新 更多