立即學習:https://edu.csdn.net/course/play/19711/343113?utm_source=blogtoedu
listbox
知識點:
1)創建listbox:
self.item_listbox = tkinter.Listbox(self.root,selectmode = "multiple", font=("微軟雅黑",12),fg = "black",bg = "white")#設置一個listbox,且為復選框(multiple),單選框(single)
2)設置復選還是單選:selectmode = "multiple"
?
3)獲得當前選擇項的索引:
?self.item_listbox.curselection()#返回的是一個列表,獲得當前listbox中被選中第一個元素的索引
?
4)根據索引獲得項目內容
self.chosen_listbox.insert('end',self.item_listbox.get(self.chosen_index))#根據索引獲得元素的內容
完整代碼:
'''
設計一個簡單的選擇listbox,由兩個listbox和兩個label以及一個按鈕組成,
將左邊選中的元素,通過點擊按鈕或者雙擊元素,自動添加到右邊的listbox中
'''
from tkinter import *
import tkinterclass mainwindow():def __init__(self):#------------創建主窗體-----------------self.root = tkinter.Tk()self.root.title("linlianqin")self.root.geometry('450x280') # 定義窗體的初始大小self.root.maxsize(1200, 1200) # 設置窗口可以顯示的最大尺寸self.item_list()self.chosen_button()self.chosen_list()self.root.mainloop() # 顯示窗口,這個代碼一定要放在所有窗口設置的后面def item_list(self):#定義列表1self.items = ["python","c","java","PHP"]#設置一個listbox元素組成的列表self.item_label = tkinter.Label(self.root,text = "請選擇你感興趣的語言:",font = ("微軟雅黑",9),fg = "white",bg = "#123333")self.item_label.grid(row = 0,column = 0)self.item_listbox = tkinter.Listbox(self.root,selectmode = "multiple", font=("微軟雅黑",12),fg = "black",bg = "white")#設置一個listbox,且為復選框(multiple),單選框(single)#將元素插入到listbox當中for item in self.items:self.item_listbox.insert("end",item)#定義雙擊選中元素自動添加到另一個列表的事件self.item_listbox.bind("<Double-Button-1>",self.button_multiple_event)self.item_listbox.grid(row = 1,column = 0)def chosen_button(self):#定義一個添加按鈕self.chosenbutton = tkinter.Button(self.root,text = "add>>>",font = ("微軟雅黑",12),fg = "black",bg = "#fffffe")self.chosenbutton.bind("<Button-1>",self.button_multiple_event)self.chosenbutton.grid(row = 1,column = 1)def chosen_list(self):#定義另一個列表,用于存放選中的元素self.chosen_label = tkinter.Label(self.root, text="感興趣的語言:", font=("微軟雅黑", 9),fg="white", bg="#123393")self.chosen_label.grid(row=0, column=2)self.chosen_listbox = tkinter.Listbox(self.root, font=("微軟雅黑", 12),fg="black", bg="white") # 設置一個listboxself.chosen_listbox.grid(row=1,column=2)def button_single_event(self,event):#定義按鈕單選事件self.chosen_index = self.item_listbox.curselection()[0]#獲得當前listbox中被選中第一個元素的索引# self.item_listbox.curselection()返回的是一個列表self.chosen_listbox.insert('end',self.item_listbox.get(self.chosen_index))#根據索引獲得元素的內容def button_multiple_event(self,event):#定義按鈕復選事件for self.chosen_index in self.item_listbox.curselection():self.chosen_listbox.insert('end',self.item_listbox.get(self.chosen_index))#若選中了就刪除該項while True:if self.item_listbox.curselection():#如果當前由被選擇中的項目self.item_listbox.delete(self.item_listbox.curselection()[0])else:breakdef main():mainwindow()if __name__ == '__main__':main()
?
?
?