【问题标题】:configuring auto-generated buttons to display different values配置自动生成的按钮以显示不同的值
【发布时间】:2021-12-27 16:10:48
【问题描述】:

我使用循环将 4 个值的列表转换为一组按钮。我需要覆盖这些按钮的文本以包含另一个列表的值(在本例中为 Ans2)。任何帮助将不胜感激。

import tkinter as tk

root = tk.Tk()

def NextQuestion():
    print("this is where i need to configure the buttons to contain values from list - Ans2")

Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]

AnsNo = 0
r = 0
c = 0
for x in range(len(Ans1)):
    AnsBtn = tk.Button(root, text=(Ans1[AnsNo]), command = NextQuestion)
    AnsBtn.grid(row=r, column=c)
    AnsNo = AnsNo+1
    if r == 1:
        c = 1
        r = 0
    else:
        r = r+1

【问题讨论】:

  • 您的意思是要配置单击的按钮以分别更改为第二个列表中对应的任何内容?就像如果我点击第二个按钮,它必须从 5 变为 9,并且剩余的按钮必须保持不变?

标签: python tkinter button


【解决方案1】:

首先,您需要将按钮存储在某个地方,以便可以访问它们进行更改。然后你只需访问他们的文本变量并更改它。

import tkinter as tk

root = tk.Tk()

def NextQuestion():
    for i, button in enumerate(buttons):
        button["text"] = Ans2[i]

Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]

buttons = []

AnsNo = 0
r = 0
c = 0
for i,answer in enumerate(Ans1):
    AnsBtn = tk.Button(root, text=(answer), command = NextQuestion)
    AnsBtn.grid(row=r, column=c)
    buttons.append(AnsBtn)
    if r == 1:
        c = 1
        r = 0
    else:
        r = r+1

root.mainloop()

【讨论】:

  • 完美运行!非常感谢。
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多