【问题标题】:Create and call Variables In a for loop在 for 循环中创建和调用变量
【发布时间】:2017-11-06 17:30:30
【问题描述】:

我正在尝试让用户输入一个数字,并使用 TKinter 创建该数量的按钮,我尝试使用以下方法来做到这一点,成功创建按钮的位置,但是我正在努力调用它们以便将它们放置/显示在网格上(添加 randint 以模拟用户输入(用户输入不限于 9,可能高达 40))

from tkinter import *
from random import randint
inputValue = randint(3,9)
print(inputValue)
root = Tk()
while inputValue > 0: # for every number in inputted value
    inputValue = int(inputValue) - 1 # take one
    globals()['Sailor%s' % inputValue] = Button(root, text="Lap :" + str(inputValue), command=lambda: retrieve_input())  # Create the button function in the format 'Sailors{Inputnumber}'
    ('Sailors%s' % inputValue).grid(row=inputValue, column=1, columnspan=2)  # Place the button (Doesn't work)
root.mainloop()  # Does work (required)

但是以下不起作用(这是为了放置按钮),

('Sailors%s' % inputValue).grid(row=inputValue, column=1, columnspan=2)  # Place the button (Doesn't work)

你能想出一种我可以用来创建和放置按钮数量的方法吗? 提前致谢

【问题讨论】:

  • 答案指出您必须使用globals 字典来执行此操作。但这提出了一个问题:为什么您首先不只是使用dict 或任何其他容器来执行此操作?

标签: python loops variables tkinter


【解决方案1】:

你不应该像你试图做的那样创建动态变量名。它增加了很多复杂性,降低了清晰度,并且没有提供任何真正的好处。

改为使用字典或列表来跟踪按钮。但是,在您的情况下,由于您从未在任何地方使用按钮,而是在循环中,您可以只使用局部变量。

使用局部变量的示例,以防您在创建按钮后不再需要访问代码中的按钮:

for count in range(inputValue):
    button = Button(...)
    button.grid(...)

如果您需要稍后在代码中访问按钮,请按以下步骤操作:

buttons = []
for count in range(inputValue):
    button = Button(...)
    button.grid(...)
    buttons.append(button)

通过以上你可以遍历buttons中的所有按钮:

for button in buttons:
    button.configure(state='disabled')

如果你需要配置单个按钮,使用它的索引:

button[0].configure(...)

【讨论】:

  • 这只会在我尝试时创建一个按钮?
  • @ItzKmaf:不,它创建的按钮数量与您指定的数量一样多。我实际上只是在您的代码中用button 替换了globals()['Sailor%s' % inputValue],当我运行它时,我得到了6 个按钮。
  • 我错了,对不起
【解决方案2】:

您现在可以在字符串上调用 grid ,这会引发错误。

您需要将('Sailors%s' % inputValue) 替换为globals()['Sailor%s' % inputValue],并将您的按钮排列在单独的行上,标记为0-8。

所以,您当前的代码是:

from tkinter import *
from random import randint
inputValue = randint(3,9)
print(inputValue)
root = Tk()
while inputValue > 0: # for every number in inputted value
    inputValue = int(inputValue) - 1 # take one
    globals()['Sailor%s' % inputValue] = Button(root, text="Lap :" + str(inputValue), command=lambda: retrieve_input())  # Create the button function in the format 'Sailors{Inputnumber}'
    globals()['Sailor%s' % inputValue].grid(row=inputValue, column=1, columnspan=2)  
root.mainloop()  # Does work (required)

retrieve_input被定义后,代码就可以正常工作了。

需要指出的是,您可以使用inputValue -= 1,而不是inputValue = int(inputValue) - 1

【讨论】:

  • 谢谢...我使用了 'int(inputValue)' 因为用户的输入是 str 格式,这样做似乎比 'inputValue=int(inputValue)' 更有效'inputValue -= 1'
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2012-01-21
  • 2020-05-18
相关资源
最近更新 更多