tk画图

时间:2023-12-23 20:44:25

Page 387 of chapter 7tk画图

 """
6-23 page 343 play media files
"""
def odd():
funcs=[]
for c in 'abcdwe':
funcs.append((lambda:c))
return funcs def odd2():
funcs=[]
for c in 'abcdwe':
funcs.append((lambda c=c:c))
return funcs def odd1():
funcs=[]
for c in 'abcdwe':
funcs.append(c)
return funcs for func in odd():
print(func())
print('force to remenber'+'#'*30)
for func in odd2():
print(func()) listt=[]
listt=odd1()
print listt

tk画图

 """
programming pytyon page 422
pop up three new windows ,with style
desctory() kill one window,quit kill all windows and app
top-level window have litle,icon,iconify/deiconify and protocol for wn events
there always is an application root window,whether by default or created as an
explicit tk() object;all top-level windows are containters but they are never
packed.gridded;toplevel is like Frame,but a new window,and can have a menu;
"""
from Tkinter import *
root =Tk()
trees =[('the larch!','light blue'),('the pine!','light green'),('the giant redwood','red')] for (tree,color) in trees:
win = Toplevel(root)
win.title('sing...')
win.protocol('WM_DELETE_WINDOW',lambda:None) #ignore close,so no meaning to close win by X
win.iconbitmap('C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\bg.ico') msg =Button(win,text=tree,command=win.destroy)
msg.pack(expand=YES,fill=BOTH)
msg.config(padx=10,pady=10,bd=10,relief=RAISED)
msg.config(bg='black',fg=color,font=('times',30,'bold italic'))
root.title('lxk demo with three win')
Label(root,text='main win',width=30).pack()
Button(root,text='quit all',command=root.quit).pack()
root.mainloop()

1. win.protocol('WM_DELETE_WINDOW',lambda:None)                           #ignore close,so no meaning to close win by X

如果设置protocol属性为None ,所以我们无法通过X关闭3个窗口

2.关掉一个窗口和对应的子窗口,使用destroy;关掉所有的窗口,使用quit

3.title设置title,iconbitmap设定图标

4.如果设定win=Toplevel(),并且还没有设定Tk root窗口,则此句将默认生成TK root作为Toplevel的主窗口。但是,我们

root=tk(),以上调用将产生产生一个root主窗口

tk画图

多个按钮放入对话框中

退出按钮:

 """
a quit button that verifies exit requests to reuse,
attach an instance to other GUIS,and repack as desired
"""
from Tkinter import *
from tkMessageBox import askokcancel class Quitter(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.pack()
wid =Button(self,text ='Quit',fg='blue',command =self.quit)
wid.pack(side =LEFT,expand =YES,fill=BOTH)
def quit(self):
ans =askokcancel('verify exit',"readlly quit")
if ans:
Frame.quit(self)
if __name__ =='__main__':
Quitter().mainloop()

对话框

 """
define a name:callback demos table
"""
from tkFileDialog import askopenfilename
from tkColorChooser import askcolor
from tkMessageBox import askquestion,showwarning
from tkSimpleDialog import askfloat demos ={
'open':askopenfilename,
'Color':askcolor,
'Query':lambda:askquestion('waring','you type q\n confirm?'),
'Error':lambda:showerror('error!',"he is here,lxk"),
'input':lambda:askfloat('entry','entry random float num')
}

组合对话框:

 "create a bar of simple buttons that launch dialog  demos"
from Tkinter import *
from dialogTable import demos
from quitter import Quitter root =Tk() class Demo(Frame):
def __init__(self,parent=None,**options):
Frame.__init__(self,parent,**options)
self.pack(fill=BOTH) #if fill no setting ,
Label(self,text ="basic demos",fg='black').pack()
for (key,value) in demos.items():
Button(self,text=key,fg="blue",command=value).pack(expand =YES,fill=BOTH)
Quitter(self).pack(side=TOP,fill=BOTH) if __name__ =='__main__':
#maindlg=Toplevel(root)
#maindlg.title('another dlg')
#maindlg.iconbitmap('C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\bg.ico')
#Button(maindlg,text='botton at maingld').pack() root.title('demo dlg')
root.iconbitmap('C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\bg.ico')
Demo().mainloop()

tk画图

把main函数中注释打开,则:

demo dlg是主窗口,关闭则所有窗口关闭。

tk画图

按钮的回调函数没有传入参数,如果需要传额外的数据到handler,我们需要打包给一个能够保存或者记住这些数据的对象,这个对象完成到实际handler的调用。如何绕过这个限制

答案:使用lambda表达式。

 "create a bar of simple buttons that launch dialog  demos"
from Tkinter import *
from dialogTable import demos
from quitter import Quitter root =Tk() class Demo(Frame):
def __init__(self,parent=None,**options):
Frame.__init__(self,parent,**options)
self.pack(fill=BOTH) #if fill no setting ,
Label(self,text ="basic demos",fg='black').pack()
for key in demos:
func = (lambda key =key:self.printit(key))
Button(self,text=key,fg="blue",command=func).pack(expand =YES,fill=BOTH)
Quitter(self).pack(side=TOP,fill=BOTH)
def printit(self,name):
print (name,'returns ==>',demos[name]()) if __name__ =='__main__':
root.title('demo dlg')
root.iconbitmap('C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\bg.ico')
Demo().mainloop()

tk画图

Check demos

 """
create a bar of check buttons that run dialog demo
"""
from Tkinter import *
from dialogTable import demos
from quitter import Quitter class Demo(Frame):
def __init__(self,parent =None,**options):
Frame.__init__(self,parent=None,**options)
self.pack()
self.tools()
Label(self,text ='check demos').pack()
self.vars = []
for key in demos:
var= IntVar()
Checkbutton(self,text =key,variable =var,command=demos[key]).pack(side =LEFT)
self.vars.append(var)
def report(self):
for var in self.vars:
print(var.get())
print()
def tools(self):
frm=Frame(self)
frm.pack(side =RIGHT)
Button(frm,text ='state',command =self.report).pack(fill =X)
Quitter(frm).pack(fill=X) if __name__=='__main__':
Demo().mainloop()

tk画图

Radiocheck

 "create a group of radio buttons that launch dialog demos"

 from Tkinter import *
from dialogTable import demos
from quitter import Quitter class Demo(Frame):
def __init__(self,parent =None,**options):
Frame.__init__(self,parent,**options)
self.pack()
Label(self,text ='radio demos').pack(side =TOP)
self.var = StringVar()
for key in demos:
Radiobutton(self,text =key,command=self.onPress,variable =self.var,
value =key).pack(anchor =NW)
self.var.set(key) #select last to start
Button(self,text ='state',command=self.report).pack(fill=X)
Quitter(self).pack(fill=X)
def onPress(self):
pick = self.var.get()
print('you pressed',pick)
print('result:',demos[pick]())
def report(self):
print(self.var.get())
if __name__=='__main__':
Demo().mainloop()

tk画图

scale check

 "create two linked scales used to launch dialog demos"

 from Tkinter import *
from dialogTable import demos
from quitter import Quitter class Demo(Frame):
def __init__(self,parent=None,**options):
Frame.__init__(self,parent,**options)
self.pack()
Label(self,text ='scale demos').pack()
self.var = IntVar()
Scale(self,label ='pick demo num',
command=self.onMove,
variable=self.var,
from_=0,to=len(demos)-1).pack()
Scale(self,label='pick demo number',
command=self.onMove,
variable=self.var,
from_=-100,to=len(demos)-1+100,
length=200,tickinterval=10,resolution=30,
showvalue=YES,orient='horizontal').pack()
Quitter(self).pack(side=RIGHT)
Button(self,text ='run demo',command=self.onRun).pack(side =LEFT)
Button(self,text ='state',command=self.report).pack(side=RIGHT)
def onMove(self,value):
print('in move',value)
def onRun(self):
pos = self.var.get()
print('you picked',pos)
demo=list(demos.values())[pos]
print(demo()) def report(self):
print self.var.get()
if __name__ =='__main__':
print(list(demos.keys()))
Demo().mainloop()

tk画图

DemoALL

 """
4 demo class components(subframes) on one window;
there are 5 quitter buttons on this one window too,and each kills entire gui
gui can be resued as frames in container,indenpendent windown or process
"""
#-*- coding: utf-8 -*-
from Tkinter import *
from quitter import Quitter
demosModules =['demoDlg','demoCheck','demoRadio','demoScale']
parts =[]
def addComponents(root):
for demo in demosModules:
module=__import__(demo)
part =module.Demo(root)
part.config(bd=2,relief=GROOVE)
part.pack(side=LEFT,expand=YES,fill=BOTH)
parts.append(part)
def dumpState():
for part in parts:
print(part.__module__+':')
if hasattr(part,'report'):
part.report()
else:
print('none') root=Tk()
root.title('主框架'.decode('gbk'))
Label(root,text ='多个框结构实例'.decode('gbk'),bg='white').pack()
Button(root,text ='状态'.decode('gbk'),command=dumpState).pack(fill=X)
Quitter(root).pack(fill=X)
addComponents(root)
root.iconbitmap('C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\bg.ico')
root.mainloop()

tk画图

Buttonbar

 """
check and radio button bar classes for apps that fetch state later
pass a list of options ,call state(),variable details automated
""" from Tkinter import *
class Checkbar(Frame):
def __init__(self,parent= None,picks =[],side=LEFT,anchor=W):
Frame.__init__(self,parent)
self.vars=[]
for pick in picks:
var = IntVar()
chk =Checkbutton(self,text =pick,variable =var)
chk.pack(side=side,anchor=anchor,expand=YES)
self.vars.append(var)
def state(self):
return [var.get() for var in self.vars]
class Radiobar(Frame):
def __init__(self,parent=None,picks=[],side=LEFT,anchor=W):
Frame.__init__(self,parent)
self.var=StringVar()
self.var.set(picks[0])
for pick in picks:
rad =Radiobutton(self,text =pick,value=pick,variable=self.var)
rad.pack(side=side,anchor=anchor)
def state(self):
return self.var.get() if __name__=='__main__':
root=Tk()
lng=Checkbar(root,['python','C#','Jave','C++'])
gui=Radiobar(root,['Win','x86','mac'],side =TOP,anchor=NW)
tgl=Checkbar(root,['All']) gui.pack(side=LEFT,fill=Y)
lng.pack(side=TOP,fill=X)
tgl.pack(side=LEFT)
lng.config(relief=GROOVE,bd=2)
gui.config(relief=RIDGE,bd=2) def allstates():
print(gui.state(),lng.state(),tgl.state())
from quitter import Quitter
Quitter(root).pack(side=RIGHT)
Button(root,text ='Peek',command=allstates).pack()
root.mainloop()

tk画图

ButtonPic

 from Tkinter import *
from glob import glob
import demoCheck
import random
gifdir='C:\\Users\\xlian7164584\\Documents\\GitHub\\R_D\\gif\\' def draw():
name,photo =random.choice(images)
lbl.config(text =name)
pix.config(image=photo) root =Tk()
lbl=Label(root,text ='none',bg='blue',fg='red')
pix=Button(root,text ='press me',command=draw,bg='white')
lbl.pack(fill=BOTH)
pix.pack(pady=10)
demoCheck.Demo(root,relief=SUNKEN,bd=2).pack(fill=BOTH) files=glob(gifdir+'*.gif')
images=[(x,PhotoImage(file=x)) for x in files]
print files
root.mainloop()

tk画图

ListBox

 "a simple customizable scrolled listbox component"
from Tkinter import * class ScrolledList(Frame):
def __init__(self,options,parent=None):
Frame.__init__(self,parent)
self.pack(expand=YES,fill=BOTH) # make me expandable
self.makeWidgets(options)
def handleList(self,event):
index = self.listbox.curselection() # on list double-click
label = self.listbox.get(index) # fetch selection text
self.runCommand(label) # and call action here or get(ACTIVE) def makeWidgets(self,options):
sbar=Scrollbar(self)
list=Listbox(self,relief=SUNKEN)
sbar.config(command=list.yview) #xlink sbar and list
list.config(yscrollcommand=sbar.set,fg='blue') # move one moves other
sbar.pack(side=RIGHT,fill=Y) #pack first=clip last
list.pack(side=LEFT,expand=YES,fill = BOTH) # list clipped first
pos=0
for label in options: # add to listbox
list.insert(pos,label) # or insert(END,label)
pos+=1 # or enumerate(options)
#list.config(selectmode=SINGLE,setgrid=1) # select ,resize modes
list.bind('<Double-1>',self.handleList) # set event handler
list.bind('<Button-1>',self.handleLeftClick) # mouse button clicks
list.bind('<KeyPress>',self.onkeyPress) # all key press
list.bind('<B1-Motion>',self.onLeftDrag) #click and draw
self.listbox=list
def runCommand(self,selection):
print('you selected:',selection) def onkeyPress(self,event):
print('got key press:',event.char) def handleLeftClick(self,event):
print('mouse button press')
self.showPosEvent(event) def onLeftDrag(self,event):
print('got left mouse button draw')
self.showPosEvent(event) def showPosEvent(self,event):
print('widget =%s X=%s, Y=%s' % (event.widget,event.x,event.y)) if __name__ =='__main__':
options =(('listbox and event %s' % x) for x in range(20))
ScrolledList(options).mainloop()

tk画图