1、ListBox
import tkinter as tk window = tk.Tk() window.title("The window") window.geometry("400x600") #create variable var1 = tk.StringVar() l = tk.Label(window,bg='red',width=10,textvariable=var1) l.pack() def print_selection(): #Get the currently selected text content value = lb.get(lb.curselection()) #Set the value of label to value var1.set(value) b1 = tk.Button(window,text='print selection',width=15, height=2,command=print_selection).pack() var2 = tk.StringVar() #Set the value for the variable, use a tuple here var2.set((11,12,13,14)) #Create Listbox and assign the value of var2 to listbox lb = tk.Listbox(window,listvariable=var2) list_item = [1,2,3,4] for item in list_item: #Add values from the last of the list control lb.insert('end',item) #Add the 'first' character in the first position lb.insert(1,'first') #Add the 'second' character in the second position lb.insert(2,'second') #delete the character at the second position 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()) #Create an option component, when we select one of the options with the mouse, put the value 'A' of value into the variable var, and then assign it to variable 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 ()
Note: l = tk.Label(window,bg='red',width=30,text='empty').pack() is written like this, because when the print_selection function calls the label label again, because the label has been "positioned" , the label label can no longer be found, so an error will be reported.
The error is as follows: