1、ListBox
import tkinter as tk
window = tk.Tk()
window.title("The window")
window.geometry("400x600")
#创建变量
var1 = tk.StringVar()
l = tk.Label(window,bg='red',width=10,textvariable=var1)
l.pack()
def print_selection():
#获取当前选中的文本内容
value = lb.get(lb.curselection())
#为label的值设为value
var1.set(value)
b1 = tk.Button(window,text='print selection',width=15,
height=2,command=print_selection).pack()
var2 = tk.StringVar()
#为变量设置值,此处用元组
var2.set((11,12,13,14))
#创建Listbox,将var2的值赋给listbox
lb = tk.Listbox(window,listvariable=var2)
list_item = [1,2,3,4]
for item in list_item:
#从列表控件最后一个为止加入值
lb.insert('end',item)
#在第一个位置加入'first'字符
lb.insert(1,'first')
#在第二个位置加入'second'字符
lb.insert(2,'second')
#删除第二个位置的字符
lb.delete(2)
lb.pack()
window.mainloop()
2、radiobutton
#Radiobutton
import tkinter as tk
window = tk.Tk()
window.title("The window")
window.geometry("400x300")
var = tk.StringVar()
#l = tk.Label(window,bg='red',width=30,text='empty').pack()
l = tk.Label(window,bg='red',width=30,text='empty')
l.pack()
def print_selection():
l.config(text='you have selected ' + var.get())
#创建选项部件,当我们鼠标选中了其中一个选项,把value的值‘A'放到变量var中,再赋值给varilable
r1 = tk.Radiobutton(window,text='Option A',variable=var,value='A',command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window,text='Option B',variable=var,value='B',command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window,text='Option C',variable=var,value='C',command=print_selection)
r3.pack()
window.mainloop()
注:l = tk.Label(window,bg='red',width=30,text='empty').pack() 写成这样子,由于print_selection函数再调用label标签时,由于label已经"定位"了,无法再找到label标签,因此会报错。
错误如下: