请解释这个循环如何对我有用 - Python tkinter

时间:2017-04-30 15:23:59

标签: python loops tkinter

from Tkinter import *

root = Tk()

v = IntVar()
v.set(1)  # initializing the choice, i.e. Python

languages = [
    ("Python",1),
    ("Perl",2),
    ("Java",3),
    ("C++",4),
    ("C",5)
]

def ShowChoice():
    print v.get()

Label(root, 
      text="""Choose your favourite 
programming language:""",
      justify = LEFT,
      padx = 20).pack()

for txt, val in languages:
    Radiobutton(root, 
                text=txt,
                padx = 20, 
                variable=v, 
                command=ShowChoice,
                value=val).pack(anchor=W)

mainloop()

有人可以解释这个循环如何创建radiobuttons?因为我发现很难遵循

1 个答案:

答案 0 :(得分:1)

执行此操作时:

languages = [
    ("Python",1),
    ("Perl",2),
    ("Java",3),
    ("C++",4),
    ("C",5)
]
for txt, val in languages:
    Radiobutton(..., text=txt, value=val, ...)

与此完全相同:

Radiobutton(root, text="Python", value=1, ...)
Radiobutton(root, text="Perl", value=2, ...)
Radiobutton(root, text="Java", value=3, ...)
Radiobutton(root, text="C++", value=4, ...)
Radiobutton(root, text="C", value=5, ...)