问题
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 in another part of my program....
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()
So how do I assign the currently selected font string in my Listbox to a variable?? I want to assign the currently selected font to a variable.... lets call it the MainFontVar.....I didnt put the variable in this code, cuz I have no idea how to access the currently selected font....any help would be greatly appreciated....and I apologize for my retardation.
回答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
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()
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
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()
来源:https://stackoverflow.com/questions/20274252/tkinter-how-to-assign-variable-to-currently-selected-item-in-listbox