在Python中从列表创建单选按钮?

0 投票
1 回答
4008 浏览
提问于 2025-04-17 22:30

下面的代码为列表中的每个项目创建了一个复选框:

cb_strings = ['item 1', 'item 2', 'item 3', 'item 4']

self.check_btns = []

for i in range(len(cb_strings)):
    v = StringVar()
    self.check_btns.append(Checkbutton(parent, width = 20, variable = v, anchor = W, onvalue = cb_strings[i], offvalue = '*', text = cb_strings[i] , command = self.display_selections))
    self.check_btns[i].var = v
    self.check_btns[i].deselect()
    self.check_btns[i].pack()

你能告诉我怎么做一个类似的事情,但创建单选按钮吗?

提前谢谢你 :)

1 个回答

3

这里有一个例子:

from Tkinter import *

cb_strings = ['item 1', 'item 2', 'item 3', 'item 4']

def sel():
   print "You selected the option " + str(var.get())

root = Tk()
var = StringVar()
var.set(cb_strings[0])

for item in cb_strings:
    button = Radiobutton(root, text=item, variable=var, value=item, command=sel)
    button.pack(anchor=W)

root.mainloop()

你还可以查看 “Tkinter入门”中的例子

撰写回答