亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 tkinter 列表框中對齊文本

如何在 tkinter 列表框中對齊文本

千巷貓影 2023-05-09 14:45:51
我想在 tkinter 列表框中對齊文本。我有一個帶有 reg 的字典列表。號碼、姓名和電子郵件作為每個字典中的鍵。我遍歷了列表并希望三個屬性以這樣的方式對齊,即這些詞之間的距離相等。因此,每一行中的每個單詞都必須從與之前/之后行中的單詞相同的位置開始。但是由于不同的名稱長度,對齊被打亂了。在上面的代碼中,為了簡單起見,我剛剛為 4 個學生創建了 4 個詞典,但實際上我必須管理 50 多個學生。除了列表框之外,還有另一種簡單的方法來顯示此數據,條件與上述相同嗎?from tkinter import *root = Tk()students_Box = LabelFrame(root,                    text = 'Registered Students', bd = 4,                    relief = GROOVE, labelanchor = 'n',                    font = 'Arial 10 bold', fg = 'navy blue',                    width = 850, height = 180)                            students_Box.grid_propagate(0)students_Box.pack(pady = 15)scrollbar = Scrollbar(students_Box)scrollbar.pack(side = RIGHT, fill = Y)listbox = Listbox(students_Box, width = 90, bg = 'azure', font = 'TkDefaultFont 11')listbox.pack(padx = 5, pady = 10)allStudents = [{'Reg': '2018-MC-01', 'Name': 'Usman Khan', 'Email': '[email protected]'},            {'Reg': '2018-MC-02', 'Name': 'Muhammad Ehtisham Zafar', 'Email': '[email protected]'},            {'Reg': '2018-MC-03', 'Name': 'Ali Khan', 'Email': '[email protected]'},            {'Reg': '2018-MC-04', 'Name': 'Abdullah Akram', 'Email': '[email protected]'}]   # A List of Dictionariesfor i in range(len(allStudents)):        listbox.insert(END, f"{allStudents[i]['Reg']}     {allStudents[i]['Name']}{' '*20}{allStudents[i]['Email']}")listbox.configure(yscrollcommand = scrollbar.set)scrollbar.configure(command = listbox.yview)mainloop()
查看完整描述

3 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

直接的方法是使用。ttk.Treeview根據您的情況解決方案(使用ljust填充它們):


from tkinter import *


root = Tk()


students_Box = LabelFrame(root,

                          text='Registered Students', bd=4,

                          relief=GROOVE, labelanchor='n',

                          font='Arial 10 bold', fg='navy blue',

                          width=850, height=180)


students_Box.grid_propagate(0)

students_Box.pack(pady=15)


scrollbar = Scrollbar(students_Box)

scrollbar.pack(side=RIGHT, fill=Y)


listbox = Listbox(students_Box, width=90, bg='azure', font='TkDefaultFont 11')

listbox.pack(padx=5, pady=10)


allStudents = [{'Reg': '2018-MC-01', 'Name': 'Usman Khan', 'Email': '[email protected]'},

               {'Reg': '2018-MC-02', 'Name': 'Muhammad Ehtisham Zafar', 'Email': '[email protected]'},

               {'Reg': '2018-MC-03', 'Name': 'Ali Khan', 'Email': '[email protected]'},

               {'Reg': '2018-MC-04', 'Name': 'Abdullah Akram',

                'Email': '[email protected]'}]  # A List of Dictionaries


maxspace = len(max(allStudents, key=lambda x:len(x['Name']))['Name']) + 4 # add 4 spaces.


for i in range(len(allStudents)):

    listbox.insert(END, f"{allStudents[i]['Reg']}     {allStudents[i]['Name'].ljust(maxspace)}{allStudents[i]['Email']}")


listbox.configure(yscrollcommand=scrollbar.set)

scrollbar.configure(command=listbox.yview)


mainloop()

它顯示:

http://img1.sycdn.imooc.com//6459ec3d000107b206580226.jpg

查看完整回答
反對 回復 2023-05-09
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

您可以使用string formatting和固定/等寬字體:

listbox = Listbox(students_Box, width=90, bg='azure', font='Courier 11') # use a fixed/monospaced font

...

for rec in allStudents:

? ? listbox.insert(END, f"{rec['Reg']:15}{rec['Name']:30}{rec['Email']}")

如果您不喜歡硬編碼寬度,則可以計算每列的最大寬度:


widths = {key:0 for key in allStudents[0]}

for rec in allStudents:

? ? for key in rec:

? ? ? ? widths[key] = max(widths[key], len(rec[key]))


for rec in allStudents:

? ? listbox.insert(END, f"{rec['Reg']:{widths['Reg']}}? {rec['Name']:{widths['Name']}}? {rec['Email']}")


查看完整回答
反對 回復 2023-05-09
?
LEATH

TA貢獻1936條經驗 獲得超7個贊

您可以嘗試以下代碼。您必須使用等寬字體才能使腳本正常工作


from tkinter import *


root = Tk()


students_Box = LabelFrame(root,

                    text = 'Registered Students', bd = 4,

                    relief = GROOVE, labelanchor = 'n',

                    font = 'Arial 10 bold', fg = 'navy blue',

                    width = 850, height = 180)

                            

students_Box.grid_propagate(0)

students_Box.pack(pady = 15)


scrollbar = Scrollbar(students_Box)

scrollbar.pack(side = RIGHT, fill = Y)


listbox = Listbox(students_Box, width = 90, bg = 'azure', font = ('Consolas', 10, ''))#'TkDefaultFont 11')

listbox.pack(padx = 5, pady = 10)


allStudents = [{'Reg': '2018-MC-01', 'Name': 'Usman Khan', 'Email': '[email protected]'},

            {'Reg': '2018-MC-02', 'Name': 'Muhammad Ehtisham Zafar', 'Email': '[email protected]'},

            {'Reg': '2018-MC-03', 'Name': 'Ali Khan', 'Email': '[email protected]'},

            {'Reg': '2018-MC-04', 'Name': 'Abdullah Akram', 'Email': '[email protected]'}]   # A List of Dictionaries


MaxRegLength = len(max(allStudents, key=lambda s: len(s['Reg']))['Reg'])

MaxNameLength = len(max(allStudents, key=lambda s: len(s['Name']))['Name'])

print(MaxRegLength, MaxNameLength)

# MaxEmailLength = max(allStudents, key=lambda s: len(s['name']))


for i in range(len(allStudents)):

    listbox.insert(END, 

    '%s         %s          %s'%(allStudents[i]['Reg'].ljust(MaxRegLength), allStudents[i]['Name'].ljust(MaxNameLength), allStudents[i]['Email']))

    # f"{allStudents[i]['Reg'].ljust(MaxRegLength)}       {allStudents[i]['Name'].ljust(MaxNameLength)}       {allStudents[i]['Email']}")


listbox.configure(yscrollcommand = scrollbar.set)

scrollbar.configure(command = listbox.yview)


mainloop()


查看完整回答
反對 回復 2023-05-09
  • 3 回答
  • 0 關注
  • 281 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號