2013-11-28 50 views
1

我需要一個Python3.3 Tkinter可滾動列表框的幫助,該列表框可遍歷所有用戶安裝的字體。該功能的目的是爲了改變字體,我在我的程序的其他部分文本字段....Tkinter - 如何將變量分配給Listbox中當前選定的項目?

from tkinter import * 
import tkinter.font 

def fontValue(): 
    fontroot=Tk() 
    fontroot.wm_title('FONTS') 

    fonts=list(tkinter.font.families()) 
    fonts.sort() 

    fontbox = Listbox(fontroot,height=20) 
    fontbox.pack(fill=BOTH, expand=YES, side=LEFT) 

    scroll = Scrollbar(fontroot) 
    scroll.pack(side=RIGHT, fill=Y, expand=NO) 

    scroll.configure(command=fontbox.yview) 
    fontbox.configure(yscrollcommand=scroll.set) 



    for item in fonts: 
     fontbox.insert(END, item) 

    fontroot.mainloop() 

那麼,如何分配當前所選字體串在我的列表框的變量?我想將當前選定的字體分配給一個變量....讓我們把它稱爲MainFontVar .....我沒有把變量放在這個代碼中,因爲我不知道如何訪問當前選定的字體....任何幫助將不勝感激....我爲我的阻滯道歉。

回答

1

由於小部件只能提供選定的索引,因此您需要保留字體列表。沿着線的東西:

from tkinter import * 
import tkinter.font 

class Main(Tk): 
    def __init__(self, *args, **kwargs): 
     Tk.__init__(self, *args, **kwargs) 

     self.fonts = list(tkinter.font.families()) 
     self.fonts.sort() 

     self.list = Listbox(self) 
     for item in self.fonts: 
      self.list.insert(END, item) 
     self.list.pack(side=LEFT, expand=YES, fill=BOTH) 
     self.list.bind("<<ListboxSelect>>", self.PrintSelected) 

     self.scroll = Scrollbar(self) 
     self.scroll.pack(side=RIGHT, fill=Y) 

     self.scroll.configure(command=self.list.yview) 
     self.list.configure(yscrollcommand=self.scroll.set) 

    def PrintSelected(self, e): 
     print(self.fonts[int(self.list.curselection()[0])]) 

root = Main() 
root.mainloop() 

一個偉大的Tk的教程位於http://www.tkdocs.com/

要獲得(在我的情況下,在Windows上)更好的外觀和感覺,你可以使用ttkScrollbar和禁用強調的活化元素在Listbox(它沒有主題變體)。

from tkinter import ttk 
from tkinter import * 
import tkinter.font 

class Main(Tk): 
    def __init__(self, *args, **kwargs): 
     Tk.__init__(self, *args, **kwargs) 

     self.fonts = list(tkinter.font.families()) 
     self.fonts.sort() 

     self.list = Listbox(self, activestyle=NONE) 
     for item in self.fonts: 
      self.list.insert(END, item) 
     self.list.pack(side=LEFT, expand=YES, fill=BOTH) 
     self.list.bind("<<ListboxSelect>>", self.PrintSelected) 

     self.scroll = ttk.Scrollbar(self) 
     self.scroll.pack(side=RIGHT, fill=Y) 

     self.scroll.configure(command=self.list.yview) 
     self.list.configure(yscrollcommand=self.scroll.set) 

    def PrintSelected(self, e): 
     print(self.fonts[int(self.list.curselection()[0])]) 

root = Main() 
root.mainloop() 
相關問題