• tk画图


     Page 387 of chapter 7

     1 """
     2 6-23 page 343 play media files
     3 """
     4 def odd():
     5     funcs=[]
     6     for c in 'abcdwe':
     7         funcs.append((lambda:c))
     8     return funcs
     9 
    10 def odd2():
    11     funcs=[]
    12     for c in 'abcdwe':
    13         funcs.append((lambda c=c:c))
    14     return funcs    
    15    
    16 def odd1():
    17     funcs=[]
    18     for c in 'abcdwe':
    19         funcs.append(c)
    20     return funcs
    21 
    22 for func in odd():
    23     print(func())
    24 print('force to remenber'+'#'*30)
    25 for func in odd2():
    26     print(func())
    27     
    28 listt=[]
    29 listt=odd1()
    30 print listt
    View Code

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

    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主窗口

    多个按钮放入对话框中

    退出按钮:

     1 """
     2 a quit button that verifies exit requests to reuse,
     3 attach an instance to other GUIS,and repack as desired
     4 """
     5 from Tkinter import  *
     6 from tkMessageBox import askokcancel
     7 
     8 class Quitter(Frame):
     9     def __init__(self,parent=None):
    10         Frame.__init__(self,parent)
    11         self.pack()
    12         wid =Button(self,text ='Quit',fg='blue',command =self.quit)
    13         wid.pack(side =LEFT,expand =YES,fill=BOTH)
    14     def quit(self):
    15         ans =askokcancel('verify exit',"readlly quit")
    16         if ans:
    17             Frame.quit(self)
    18 if __name__ =='__main__':
    19     Quitter().mainloop()
    View Code

    对话框

     1 """
     2 define a name:callback demos table
     3 """
     4 from tkFileDialog import askopenfilename
     5 from tkColorChooser import askcolor
     6 from tkMessageBox import askquestion,showwarning
     7 from tkSimpleDialog import askfloat
     8 
     9 demos ={
    10     'open':askopenfilename,
    11     'Color':askcolor,
    12     'Query':lambda:askquestion('waring','you type q
     confirm?'),
    13     'Error':lambda:showerror('error!',"he is here,lxk"),
    14     'input':lambda:askfloat('entry','entry random float num')
    15 }
    View Code

    组合对话框:

     1 "create a bar of simple buttons that launch dialog  demos"
     2 from Tkinter import *
     3 from dialogTable import demos
     4 from quitter import Quitter
     5 
     6 root =Tk()
     7 
     8 class Demo(Frame):
     9     def __init__(self,parent=None,**options):
    10         Frame.__init__(self,parent,**options)
    11         self.pack(fill=BOTH) #if fill no setting ,
    12         Label(self,text ="basic demos",fg='black').pack()
    13         for (key,value) in demos.items():
    14             Button(self,text=key,fg="blue",command=value).pack(expand =YES,fill=BOTH)
    15         Quitter(self).pack(side=TOP,fill=BOTH)
    16 
    17 if __name__ =='__main__':
    18     #maindlg=Toplevel(root)
    19     #maindlg.title('another dlg')
    20     #maindlg.iconbitmap('C:\Users\xlian7164584\Documents\GitHub\R_D\bg.ico')
    21     #Button(maindlg,text='botton at maingld').pack()
    22     
    23     root.title('demo dlg')
    24     root.iconbitmap('C:\Users\xlian7164584\Documents\GitHub\R_D\bg.ico')    
    25     Demo().mainloop()
    View Code

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

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

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

    答案:使用lambda表达式。

     1 "create a bar of simple buttons that launch dialog  demos"
     2 from Tkinter import *
     3 from dialogTable import demos
     4 from quitter import Quitter
     5 
     6 root =Tk()
     7 
     8 class Demo(Frame):
     9     def __init__(self,parent=None,**options):
    10         Frame.__init__(self,parent,**options)
    11         self.pack(fill=BOTH) #if fill no setting ,
    12         Label(self,text ="basic demos",fg='black').pack()
    13         for key in demos:
    14             func = (lambda key =key:self.printit(key))
    15             Button(self,text=key,fg="blue",command=func).pack(expand =YES,fill=BOTH)
    16         Quitter(self).pack(side=TOP,fill=BOTH)
    17     def printit(self,name):
    18         print (name,'returns ==>',demos[name]())
    19 
    20 if __name__ =='__main__':
    21     root.title('demo dlg')
    22     root.iconbitmap('C:\Users\xlian7164584\Documents\GitHub\R_D\bg.ico')    
    23     Demo().mainloop()
    View Code

    Check demos

     1 """
     2 create a bar of check buttons that run dialog demo
     3 """
     4 from Tkinter import *
     5 from dialogTable import demos
     6 from quitter import Quitter
     7 
     8 class Demo(Frame):
     9     def __init__(self,parent =None,**options):
    10         Frame.__init__(self,parent=None,**options)
    11         self.pack()
    12         self.tools()
    13         Label(self,text ='check demos').pack()
    14         self.vars = []
    15         for key in demos:
    16             var= IntVar()
    17             Checkbutton(self,text =key,variable =var,command=demos[key]).pack(side =LEFT)
    18             self.vars.append(var)
    19     def report(self):
    20         for var in self.vars:
    21             print(var.get())
    22         print()
    23     def tools(self):
    24         frm=Frame(self)
    25         frm.pack(side =RIGHT)
    26         Button(frm,text ='state',command =self.report).pack(fill =X)
    27         Quitter(frm).pack(fill=X)
    28 
    29 if __name__=='__main__':
    30     Demo().mainloop()
    View Code

    Radiocheck

     1 "create a group of radio buttons that launch dialog demos"
     2 
     3 from Tkinter import *
     4 from dialogTable import demos
     5 from quitter import Quitter
     6 
     7 class Demo(Frame):
     8     def __init__(self,parent =None,**options):
     9         Frame.__init__(self,parent,**options)
    10         self.pack()
    11         Label(self,text ='radio demos').pack(side =TOP)
    12         self.var = StringVar()
    13         for key in demos:
    14             Radiobutton(self,text =key,command=self.onPress,variable =self.var,
    15                         value =key).pack(anchor =NW)
    16         self.var.set(key) #select last to start
    17         Button(self,text ='state',command=self.report).pack(fill=X)
    18         Quitter(self).pack(fill=X)
    19     def onPress(self):
    20         pick = self.var.get()
    21         print('you pressed',pick)
    22         print('result:',demos[pick]())
    23     def report(self):
    24         print(self.var.get())
    25 if __name__=='__main__':
    26     Demo().mainloop()
    View Code

    scale check

     1 "create two linked scales used to launch dialog demos"
     2 
     3 from Tkinter import *
     4 from dialogTable import demos
     5 from quitter import Quitter
     6 
     7 class Demo(Frame):
     8     def __init__(self,parent=None,**options):
     9         Frame.__init__(self,parent,**options)
    10         self.pack()
    11         Label(self,text ='scale demos').pack()
    12         self.var = IntVar()
    13         Scale(self,label ='pick demo num',
    14               command=self.onMove,
    15               variable=self.var,
    16               from_=0,to=len(demos)-1).pack()
    17         Scale(self,label='pick demo number',
    18               command=self.onMove,
    19               variable=self.var,
    20               from_=-100,to=len(demos)-1+100,
    21               length=200,tickinterval=10,resolution=30,
    22               showvalue=YES,orient='horizontal').pack()
    23         Quitter(self).pack(side=RIGHT)
    24         Button(self,text ='run demo',command=self.onRun).pack(side =LEFT)
    25         Button(self,text ='state',command=self.report).pack(side=RIGHT)
    26     def onMove(self,value):
    27         print('in move',value)
    28     def onRun(self):
    29         pos = self.var.get()
    30         print('you picked',pos)
    31         demo=list(demos.values())[pos]
    32         print(demo())
    33         
    34     def report(self):
    35         print self.var.get()
    36 if __name__ =='__main__':
    37     print(list(demos.keys()))
    38     Demo().mainloop()
    39         
    View Code

    DemoALL

     1 """
     2 4 demo class components(subframes) on one window;
     3 there are 5 quitter buttons on this one window too,and each kills entire gui
     4 gui can be resued as frames in container,indenpendent windown or process
     5 """
     6 #-*- coding: utf-8 -*-
     7 from Tkinter import *
     8 from quitter import Quitter
     9 demosModules =['demoDlg','demoCheck','demoRadio','demoScale']
    10 parts =[]
    11 def addComponents(root):
    12     for demo in demosModules:
    13         module=__import__(demo)
    14         part =module.Demo(root)
    15         part.config(bd=2,relief=GROOVE)
    16         part.pack(side=LEFT,expand=YES,fill=BOTH)
    17         parts.append(part)
    18 def dumpState():
    19     for part in parts:
    20         print(part.__module__+':')
    21         if hasattr(part,'report'):
    22             part.report()
    23         else:
    24             print('none')
    25 
    26 root=Tk()
    27 root.title('主框架'.decode('gbk'))
    28 Label(root,text ='多个框结构实例'.decode('gbk'),bg='white').pack()
    29 Button(root,text ='状态'.decode('gbk'),command=dumpState).pack(fill=X)
    30 Quitter(root).pack(fill=X)
    31 addComponents(root)
    32 root.iconbitmap('C:\Users\xlian7164584\Documents\GitHub\R_D\bg.ico')   
    33 root.mainloop()
    View Code

    Buttonbar

     1 """
     2 check and radio button bar classes for apps that fetch state later
     3 pass a list of options ,call state(),variable details automated
     4 """
     5 
     6 from Tkinter import *
     7 class Checkbar(Frame):
     8     def __init__(self,parent= None,picks =[],side=LEFT,anchor=W):
     9         Frame.__init__(self,parent)
    10         self.vars=[]
    11         for pick in picks:
    12             var = IntVar()
    13             chk =Checkbutton(self,text =pick,variable =var)
    14             chk.pack(side=side,anchor=anchor,expand=YES)
    15             self.vars.append(var)
    16     def state(self):
    17         return [var.get() for var in self.vars]
    18 class Radiobar(Frame):
    19     def __init__(self,parent=None,picks=[],side=LEFT,anchor=W):
    20         Frame.__init__(self,parent)
    21         self.var=StringVar()
    22         self.var.set(picks[0])
    23         for pick in picks:
    24             rad =Radiobutton(self,text =pick,value=pick,variable=self.var)
    25             rad.pack(side=side,anchor=anchor)
    26     def state(self):
    27         return self.var.get()
    28     
    29 if __name__=='__main__':
    30     root=Tk()
    31     lng=Checkbar(root,['python','C#','Jave','C++'])
    32     gui=Radiobar(root,['Win','x86','mac'],side =TOP,anchor=NW)
    33     tgl=Checkbar(root,['All'])
    34     
    35     gui.pack(side=LEFT,fill=Y)
    36     lng.pack(side=TOP,fill=X)
    37     tgl.pack(side=LEFT)
    38     lng.config(relief=GROOVE,bd=2)
    39     gui.config(relief=RIDGE,bd=2)
    40     
    41     def allstates():
    42         print(gui.state(),lng.state(),tgl.state())
    43     from quitter import Quitter
    44     Quitter(root).pack(side=RIGHT)
    45     Button(root,text ='Peek',command=allstates).pack()
    46     root.mainloop()
    View Code

    ButtonPic

     1 from Tkinter import *
     2 from glob import glob
     3 import demoCheck
     4 import random
     5 gifdir='C:\Users\xlian7164584\Documents\GitHub\R_D\gif\'
     6 
     7 def draw():
     8     name,photo =random.choice(images)
     9     lbl.config(text =name)
    10     pix.config(image=photo)
    11     
    12 root =Tk()
    13 lbl=Label(root,text ='none',bg='blue',fg='red')
    14 pix=Button(root,text ='press me',command=draw,bg='white')
    15 lbl.pack(fill=BOTH)
    16 pix.pack(pady=10)
    17 demoCheck.Demo(root,relief=SUNKEN,bd=2).pack(fill=BOTH)
    18 
    19 files=glob(gifdir+'*.gif')
    20 images=[(x,PhotoImage(file=x)) for x in files]
    21 print files
    22 root.mainloop()
    View Code

    ListBox

     1 "a simple customizable scrolled listbox component"
     2 from Tkinter import *
     3 
     4 class ScrolledList(Frame):
     5     def __init__(self,options,parent=None):
     6         Frame.__init__(self,parent)
     7         self.pack(expand=YES,fill=BOTH)     # make me expandable
     8         self.makeWidgets(options)
     9     def handleList(self,event):
    10         index = self.listbox.curselection()   # on list double-click
    11         label = self.listbox.get(index)       # fetch selection text
    12         self.runCommand(label)                # and call action here or get(ACTIVE)
    13         
    14     def makeWidgets(self,options):
    15         sbar=Scrollbar(self)
    16         list=Listbox(self,relief=SUNKEN)
    17         sbar.config(command=list.yview)             #xlink sbar and list
    18         list.config(yscrollcommand=sbar.set,fg='blue')        # move one moves other
    19         sbar.pack(side=RIGHT,fill=Y)                #pack first=clip last
    20         list.pack(side=LEFT,expand=YES,fill = BOTH) # list clipped first
    21         pos=0
    22         for label in options:                       # add to listbox
    23             list.insert(pos,label)                   # or insert(END,label)
    24             pos+=1                                   # or enumerate(options)
    25         #list.config(selectmode=SINGLE,setgrid=1)    # select ,resize modes
    26         list.bind('<Double-1>',self.handleList)      # set event handler
    27         list.bind('<Button-1>',self.handleLeftClick) # mouse button clicks
    28         list.bind('<KeyPress>',self.onkeyPress)      # all key press
    29         list.bind('<B1-Motion>',self.onLeftDrag)     #click and draw
    30         self.listbox=list
    31     def runCommand(self,selection):
    32         print('you selected:',selection)
    33         
    34     def onkeyPress(self,event):
    35         print('got key press:',event.char)
    36         
    37     def handleLeftClick(self,event):
    38         print('mouse button press')
    39         self.showPosEvent(event)
    40     
    41     def onLeftDrag(self,event):
    42         print('got left mouse button draw')
    43         self.showPosEvent(event)
    44         
    45     def showPosEvent(self,event):
    46         print('widget =%s X=%s, Y=%s' % (event.widget,event.x,event.y))
    47 
    48 if __name__ =='__main__':
    49     options =(('listbox and event %s' % x) for x in range(20))
    50     ScrolledList(options).mainloop()
    51         
    View Code

  • 相关阅读:
    [Java123] JDBC and Multi-Threading 多线程编程学习笔记
    3:2D装换 [ 重点 ]
    2:属性选择器 + 结构伪类选择器 + 伪元素
    1:新增 H5 常用属性
    day2
    代码实操第一天
    1 滑动门
    css高级技巧
    11:网页布局总结
    10:定位
  • 原文地址:https://www.cnblogs.com/lxk613/p/4848223.html
Copyright © 2020-2023  润新知