Tk Tutorial - 7. More Widgets

Listbox

Listboxes are created using the Listbox function:

l = Listbox(parent, height=10)

Populating the Listbox Items

Each listbox has a "listvariable" configuration option, which allows you to link a variable (which must hold a list) to the listbox. Each element of this listis a string representing one item in the listbox. So to add, remove, or rearrangeitems in the listbox, you can simply manipulate this variable as you would any otherlist.

Selecting Items

The first thing you need to decide is whether it is possible for the user to select only a single item at a time, or if multiple items can simultaneously be selected. This is controlled by the "selectmode" option: the default is only being able to selecta single item ("browse"), while a selectmode of "extended" allows the user to select multiple items.

Stylizing the List

You canmodify the font the listbox items are displayed in, the foreground (text) and background colors for itemsin their normal state, when selected, when the widget is disabled, and so on. There is also an"itemconfigure" method which allows you to change the foreground and background colors ofindividual items.

Keeping Extra Item Data

The "listvariable" (or the internal list, if you're managing things the old way) contains the strings that will be shown in the listbox.

Example

from tkinter import *
from tkinter import ttk

root = Tk()

# Initialize our country "databases":
#  - the list of country codes (a subset anyway)
#  - a parallel list of country names, in the same order as the country codes
#  - a hash table mapping country code to population<
countrycodes = ('ar', 'au', 'be', 'br', 'ca', 'cn', 'dk', 'fi', 'fr', 'gr', 'in', 'it', 'jp', 'mx', 'nl', 'no', \
                'es', 'se', 'ch')
countrynames = ('Argentina', 'Australia', 'Belgium', 'Brazil', 'Canada', 'China', 'Denmark', \
                'Finland', 'France', 'Greece', 'India', 'Italy', 'Japan', 'Mexico', 'Netherlands', 'Norway',
                'Spain', 'Sweden', 'Switzerland')
cnames = StringVar(value = countrynames)
populations = {'ar':41000000, 'au':21179211, 'be':10584534, 'br':185971537, \
               'ca':33148682, 'cn':1323128240, 'dk':5457415, 'fi':5302000, 'fr':64102140, 'gr':11147000, \
               'in':1131043000, 'it':59206382, 'jp':127718000, 'mx':106535000, 'nl':16402414, \
               'no':4738085, 'es':45116894, 'se':9174082, 'ch':7508700}

# Names of the gifts we can send
gifts = {'card':'Greeting card', 'flowers':'Flowers', 'nastygram':'Nastygram'}

# State variables
gift = StringVar()
sentmsg = StringVar()
statusmsg = StringVar()

# Called when the selection in the listbox changes; figure out
# which country is currently selected, and then lookup its country
# code, and from that, its population.  Update the status message
# with the new population.  As well, clear the message about the
# gift being sent, so it doesn't stick around after we start doing
# other things.
def showPopulation(*args):
    idxs = lbox.curselection()
    if len(idxs) == 1:
        idx  = int(idxs[0])
        code = countrycodes[idx]
        name = countrynames[idx]
        popn = populations[code]
        statusmsg.set("The population of %s (%s) is %d" % (name, code, popn))
    sentmsg.set('')

# Called when the user double clicks an item in the listbox, presses
# the "Send Gift" button, or presses the Return key.  In case the selected
# item is scrolled out of view, make sure it is visible.
#
# Figure out which country is selected, which gift is selected with the 
# radiobuttons, "send the gift", and provide feedback that it was sent.
def sendGift(*args):
    idxs = lbox.curselection()
    if len(idxs) == 1:
        idx = int(idxs[0])
        lbox.see(idx)
        name = countrynames[idx]
        # Gift sending left as an exercise to the reader
        sentmsg.set("Sent %s to leader of %s" % (gifts[gift.get()], name))

# Create and grid the outer content frame
c = ttk.Frame(root, padding=(5, 5, 12, 0))
c.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

# Create the different widgets; note the variables that many
# of them are bound to, as well as the button callback.
# Note we're using the StringVar() 'cnames', constructed from 'countrynames'
lbox = Listbox(c, listvariable = cnames, height = 5)
lbl = ttk.Label(c, text="Send to country's leader:")
g1 = ttk.Radiobutton(c, text=gifts['card'], variable=gift, value='card');
g2 = ttk.Radiobutton(c, text=gifts['flowers'], variable=gift, value='flowers');
g3 = ttk.Radiobutton(c, text=gifts['nastygram'], variable=gift, value='nastygram');
send = ttk.Button(c, text='Send Gift', command=sendGift, default='active')
sentlbl = ttk.Label(c, textvariable=sentmsg, anchor='center');
status = ttk.Label(c, textvariable=statusmsg, anchor=W);

# Grid all the widgets
lbox.grid(column=0, row=0, rowspan=6, sticky=(N,S,E,W))
lbl.grid(column=1, row=0, padx=10, pady=5)
g1.grid(column=1, row=1, sticky=W, padx=20)
g2.grid(column=1, row=2, sticky=W, padx=20)
g3.grid(column=1, row=3, sticky=W, padx=20)
send.grid(column=2, row=4, sticky=E)
sentlbl.grid(column=1, row=5, columnspan=2, sticky=N, pady=5, padx=5)
status.grid(column=0, row=6, columnspan=2, sticky=(W,E))
c.grid_columnconfigure(0, weight=1)
c.grid_rowconfigure(5, weight=1)

# Set event bindings for when the selection in the listbox changes,
# when the user double clicks the list, and when they hit the Return key
lbox.bind('<<ListboxSelect>>', showPopulation)
lbox.bind('<Double-1>', sendGift)
root.bind('<Return>', sendGift)

# Colorize alternating lines of the listbox
for i in range(0,len(countrynames),2):
    lbox.itemconfigure(i, background='#f0f0ff')

# Set the starting state of the interface, including selecting the
# default gift to send, and clearing the messages.  Select the first
# country in the list; because the <<ListboxSelect>> event is only
# generated when the user makes a change, we explicitly call showPopulation.
gift.set('card')
sentmsg.set('')
statusmsg.set('')
lbox.selection_set(0)
showPopulation()

root.mainloop()

Scrollbar

Scrollbars are created using the ttk.Scrollbar command:

s = ttk.Scrollbar(parent, orient=VERTICAL, command=listbox.yview)
listbox.configure(yscrollcommand=s.set)
The "orient" configuration option of scrollbars determines whether it will be used toscroll in the "horizontal" or "vertical". You then need to set up the "command" configuration option to communicate with the scrolled widget.

Every widget that can be scrolled vertically includes a method named "yview" (those thatcan be scrolled horizontally have a method named "xview"). As long as this method ispresent, the scrollbar doesn't need to know anything else about the scrolled widget. When thescrollbar is manipulated, it will tack on some number of parameters to the method call, indicatinghow it was scrolled, to what position, etc.
Besides the yview and/or xview methods,every scrollable widget also has a "yscrollcommand" and/or "xscrollcommand"configuration option. This is used to specify a method call, which must be the scrollbar's"set" method.

Example

from tkinter import *
from tkinter import ttk

root = Tk()
l = Listbox(root, height = 5)
l.grid(column = 0, row = 0, sticky = (N,W,E,S))
s = ttk.Scrollbar(root, orient = VERTICAL, command = l.yview)
s.grid(column = 1, row = 0, sticky = (N,S))
l['yscrollcommand'] = s.set
ttk.Sizegrip().grid(column = 1, row = 1, sticky = (S, E))
root.grid_columnconfigure(0, weight = 1)
root.grid_rowconfigure(0, weight = 1)
for i in range(1, 101):
    l.insert('end', 'Line %d of 100' % i)
root.mainloop()

SizeGrip

This is the little box at the bottom rightcorner of the window that allows you to resize it.

SizeGrips are created using the ttk.Sizegrip function:

ttk.Sizegrip(parent).grid(column=999, row=999, sticky=(S,E))

Text

Text widgets are created using the Text function:

t = Text(parent, width=40, height=10)

Progressbar

Progessbar widgets are created using the ttk.Progessbar class:

p = ttk.Progressbar(parent, orient=HORIZONTAL, length=200, mode='determinate')

Scale

Progessbar widgets are created using the ttk.Scale function:

s = ttk.Scale(parent, orient=HORIZONTAL, length=200, from_=1.0, to=100.0)

Spinbox

Spinbox widgets are created using the Spinbox function:

spinval = StringVar()
s = Spinbox(parent, from_=1.0, to=100.0, textvariable=spinval)
from: http://www.tkdocs.com/tutorial/morewidgets.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值