【发布时间】: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