Skip to content Skip to sidebar Skip to footer

Tkinter - How To Assign Variable To Currently Selected Item In Listbox?

I need help with a Python3.3 Tkinter scrollable list box that iterates through all the users installed fonts. The purpose of this function is to change the fonts in my Textfield i

Solution 1:

You need to hold a list of your fonts as the widget can only give you the selected index. Something along the lines:

from tkinter import *
import tkinter.font

classMain(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)

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

root = Main()
root.mainloop()

A great Tk tutorial is located at http://www.tkdocs.com/

To get better look and feel (on Windows in my case), you can use ttk for Scrollbar and disable underline for activated element in Listbox (which does not have themed variant).

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

classMain(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)

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

root = Main()
root.mainloop()

Post a Comment for "Tkinter - How To Assign Variable To Currently Selected Item In Listbox?"