Код: Выделить всё
x = 0
while x < 10:
tk.Frame(r, width=50, height=50, borderwidth=1, relief='solid', bg='purple').pack()
x+=1
Код: Выделить всё
import tkinter as tk
r = tk.Tk()
# This function switches the Frame's color
def change_color(wid):
# This print function shows that only '.!Frame10' is being affected
print(wid)
if wid['bg'] == 'purple':
wid['bg'] = 'green'
elif wid['bg'] == 'green':
wid['bg'] = 'purple'
# Frames are created by functions to allow binding & packing using a temporary reference
def frame():
main = tk.Frame(r, width=50, height=50, borderwidth=1, relief='solid', bg='purple')
# This bind triggers the function which affects the frame being left-clicked
main.bind_all('', lambda a: change_color(main) )
main.pack()
# This loop creates 10 instances of the frame
x = 0
while x < 10:
frame()
x+=1
r.mainloop()
Я читал, что можно автоматизировать сохранение объектов/функций в переменных с помощью словарей, но у меня это не работает. Этот пример, который я сделал, возвращает " KeyError: '3' ", который я не понимаю.
Код: Выделить всё
import tkinter as tk
r = tk.Tk()
# This function switches the Frame's color
def change_color(x):
# This print function shows that only '.!Frame10' is being affected
print(x)
if x['bg'] == 'purple':
x['bg'] = 'green'
elif x['bg'] == 'green':
x['bg'] = 'purple'
dic = {}
# This loop creates frames and stores them in the dictionary above.
x = 1
while x < 3:
dic[str(x)] = tk.Frame(r, width=50, height=50, borderwidth=1, relief='solid', bg='purple')
dic[str(x)].bind_all('', lambda a: change_color(dic[str(x)]) )
dic[str(x)].pack()
x+=1
r.mainloop()
Будем благодарны за любую помощь.
Подробнее здесь: https://stackoverflow.com/questions/792 ... -by-a-loop
Мобильная версия