tkinter官方文档学习笔记

文档地址:http://effbot.org/tkinterbook/


主界面
root = Tk()
root.mainloop()
框架
frame = Frame(root, width=100, height=100)
frame.pack()
按钮
button = Button(frame, text="te\nxt", justify="left", wraplength="50", fg="red", font="宋体", command=func)
button.pack(side=LEFT)
fg - 前景色
bg - 背景色
可用颜色:
Red, Green, Blue, Yellow, and LightBlue 等,还可接受 #ffff00 输入
font 指定字体,可同时指定大小,加粗,斜体
font = "Helvetica 10 bold italic"
font = ("Courier New", 10, "bold italic") 注意:如果字体名称中有空格,必须采用tuple形式
可以在text属性的字符串中加入'\n'来换行
justify 用来设置文本的对齐方式,可用值为 left,right,center,默认为center
wraplength  用来设置文本的自动换行宽度,宽度单位为像素
bd 设置边框宽度,宽度单位为像素
relief 设置浮雕效果,可用值:flat, groove, raised, ridge, solid, or sunken
.bind("<Button-1>", callback)  给组件绑定事件响应函数
.focus_set()  将焦点设置在组件上。对于键盘按键事件,需要先设置焦点在组件上
"<Button-1>"  鼠标左键点击
callback(event)  
event.x, event.y  鼠标点击x,y坐标
event.char  按键码


事件描述字符串 <modifier-type-detail>
type - 是事件描述中最重要的部分,比如Button, Key, Enter, Configure等
如果仅仅为了匹配一个特定的按键,可以省略两边的尖括号,直接输入按键
常用事件:
<Button-1> 鼠标点击事件,1-左键 2-中键 3-右键
<B1-Motion> 鼠标按下后移动,1-左键 2-中键 3-右键
<ButtonRelease-1>  鼠标抬起,1-左键 2-中键 3-右键
<Double-Button-1>  鼠标双击,1-左键 2-中键 3-右键
<Enter>  鼠标进入组件范围
<Leave>  鼠标离开组件范围
<FocusIn>  焦点聚焦到组件范围
<FocusOut>  焦点离开组件范围
<Return> 按回车键
<Shift_L>  左shift键
Cancel (the Break key)
BackSpace
Tab
Control_L
Alt_L
Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock
<Key> 按下任意键盘键,event.char 返回按下的键。特殊按键返回空字符串
<space>  按下空格
<less>  左括号
<Shift-Up>  按住shift同时按上键,附加按键有Alt, Shift, and Control
<Configure>  改变组件大小 event.width event.height 返回新的大小 


bind的绑定层级
bind 绑定组件实例
bind 绑定顶级组件root
bind_class 绑定组件类
bind_all  绑定所有组件


绑定事件,后绑定覆盖先绑定
text.bind("<Return>", lambda e: "break")  屏蔽某text的回车事件
top.bind_class("Text", "<Return>", lambda e: None)  屏蔽所有Text的回车事件
官方不建议这样修改,会影响程序的拓展性,更好的解决方案是使用自定义的类
class MyText(Text):
    def __init__(self, master, **kw):
        apply(Text.__init__, (self, master), kw)
        self.bind("<Return>", lambda e: "break")


除了绑定事件外,还有协议事件。以下例子为关闭窗口时弹出是否关闭的确认框
from tkinter import *
from tkinter import messagebox


def callback():
    if messagebox.askokcancel("Quit", "Do you really wish to quit?"):
        root.destroy()


root = Tk()
root.protocol("WM_DELETE_WINDOW", callback)


root.mainloop()


创建两个窗口,Toplevel不能使用pack等布局方法
root = Tk()
top = Toplevel()
root.mainloop()


创建菜单实例
from tkinter import *


def callback():
    print "called the callback!"


root = Tk()


# create a menu
menu = Menu(root)
root.config(menu=menu)


filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)


helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)


mainloop()


使用Frame做为工具栏,如果需要使用图标,使用PhotoImage载入图片,使用image属性指定图片
root = Tk()
toolbar = Frame(root)
b = Button(toolbar, text='new', width=6, command=callback)
b.pack(side=LEFT, padx=2,pady=2)
b = Button(toolbar, text='open', width=6, command=callback)
b.pack(side=LEFT, padx=2,pady=2)
# fill=X 为填满整个宽度
toolbar.pack(side=TOP, fill=X)
root.mainloop()


root.geometry("600x480") 设置主界面大小


状态栏
status = Label(root, text="状态栏", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill= X)


消息框,可用选项为showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel
if tkMessageBox.askyesno("Print", "Print this report?"):
        report.print()


一个dialog的实例
class Dialog(Toplevel):
    def __init__(self, parent, title = None):
        Toplevel.__init__(self, parent)
        self.transient(parent)
        if title:
            self.title(title)
        self.parent = parent
        self.result = None
        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.buttonbox()
        self.grab_set()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                  parent.winfo_rooty()+50))
        self.initial_focus.focus_set()
        self.wait_window(self)
    #
    # construction hooks
    def body(self, master):
        # create dialog body.  return widget that should have
        # initial focus.  this method should be overridden
        pass


    def buttonbox(self):
        # add standard button box. override if you don't want the
        # standard buttons
        box = Frame(self)
        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)
        box.pack()
    #
    # standard button semantics
    def ok(self, event=None):
        if not self.validate():
            self.initial_focus.focus_set() # put focus back
            return
        self.withdraw()
        self.update_idletasks()
        self.apply()
        self.cancel()


    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()
    #
    # command hooks
    def validate(self):
        return 1 # override


    def apply(self):
        pass # override




class MyDialog(Dialog):
    def body(self, master):
        Label(master, text="First:").grid(row=0)
        Label(master, text="Second").grid(row=1)
        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        return self.e1
    def apply(self):
        first = int(self.e1.get())
        second = int(self.e2.get())
        print(first,second)


root = Tk()
MyDialog(root)
root.mainloop()


pack 可用属性
padx, pady 水平,垂直方向间隔
side 放置方向,LEFT TOP RIGHT BOTTOM
fill 延展方向 X-铺满


grid 可用属性
row, column 行列位置
sticky  对齐方向 W E N S 



评论 1 您还未登录,请先 登录 后发表或查看评论
Abstract Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python programming language. This publication is available in Web form1 and also as a PDF document2. Please forward any comments to tcc-doc@nmt.edu. Table of Contents 1. What is Tkinter?.......................................................................................................................3 2. A minimal application..............................................................................................................3 3. Definitions..............................................................................................................................4 4. Layout management.................................................................................................................5 4.1. The .grid() method....................................................................................................5 4.2. Other grid management methods...................................................................................6 4.3. Configuring column and row sizes.................................................................................7 4.4. Making the root window resizeable................................................................................8 5. Standard attributes...................................................................................................................8 5.1. Dimensions...................................................................................................................9 5.2. The coordinate system...................................................................................................9 5.3. Colors...........................................................................................................................9 5.4. Type fonts...................................................................................................................10 5.5. Anchors......................................................................................................................11 5.6. Relief styles.................................................................................................................12 5.7. Bitmaps.......................................................................................................................12 5.8. Cursors.......................................................................................................................12 5.9. Images........................................................................................................................14 5.10. Geometry strings........................................................................................................14 5.11. Window names...........................................................................................................15 5.12. Cap and join styles.....................................................................................................15 5.13. Dash patterns.............................................................................................................16 5.14. Matching stipple patterns............................................................................................16 6. The Button widget................................................................................................................17 7. The Canvas widget................................................................................................................19 7.1. Canvas coordinates......................................................................................................20 7.2. The Canvas display list................................................................................................20 7.3. Canvas object IDs........................................................................................................21 7.4. Canvas tags................................................................................................................21 1http://www.nmt.edu/tcc/help/pubs/tkinter/ 2http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf 1 Tkinter reference New Mexico Tech Computer Center 7.5. CanvastagOrId arguments......................................................................................21 7.6. Methods on Canvas widgets........................................................................................21 7.7. Canvas arc objects.......................................................................................................26 7.8. Canvas bitmap objects.................................................................................................28 7.9. Canvas image objects..................................................................................................29 7.10. Canvas line objects.....................................................................................................29 7.11. Canvas oval objects....................................................................................................31 7.12. Canvas polygon objects..............................................................................................32 7.13. Canvas rectangle objects.............................................................................................34 7.14. Canvas text objects.....................................................................................................35 7.15. Canvas window objects..............................................................................................36 8. The Checkbutton widget......................................................................................................37 9. The Entry widget..................................................................................................................40 9.1. Scrolling an Entry widget............................................................................................43 10. The Frame widget................................................................................................................43 11. The Label widget................................................................................................................44 12. The LabelFrame widget......................................................................................................46 13. The Listbox widget............................................................................................................48 13.1. Scrolling a Listbox widget........................................................................................52 14. The Menu widget..................................................................................................................52 14.1. Menu item creation (coption) options.........................................................................55 14.2. Top-level menus.........................................................................................................56 15. The Menubutton widget......................................................................................................57 16. The Message widget............................................................................................................59 17. The OptionMenu widget.......................................................................................................60 18. The PanedWindow widget....................................................................................................61 18.1. PanedWindow child configuration options...................................................................63 19. The Radiobutton widget....................................................................................................64 20. The Scale widget................................................................................................................67 21. The Scrollbar widget........................................................................................................70 21.1. The Scrollbarcommand callback............................................................................72 21.2. Connecting a Scrollbar to another widget................................................................73 22. The Spinbox widget............................................................................................................73 23. The Text widget..................................................................................................................78 23.1. Text widget indices...................................................................................................80 23.2. Text widget marks....................................................................................................81 23.3. Text widget images...................................................................................................82 23.4. Text widget windows...............................................................................................82 23.5. Text widget tags.......................................................................................................82 23.6. Setting tabs in a Text widget......................................................................................83 23.7. The Text widget undo/redo stack..............................................................................83 23.8. Methods on Text widgets..........................................................................................84 24. Toplevel: Top-level window methods..................................................................................91 25. Universal widget methods.....................................................................................................93 26. Standardizing appearance...................................................................................................101 26.1. How to name a widget class......................................................................................102 26.2. How to name a widget instance.................................................................................102 26.3. Resource specification lines.......................................................................................102 26.4. Rules for resource matching......................................................................................103 27. Connecting your application logic to the widgets...................................................................104 28. Control variables: the values behind the widgets...................................................................104 29. Focus: routing keyboard input.............................................................................................106 New Mexico Tech Computer Center Tkinter reference 2 30. Events................................................................................................................................107 30.1. Levels of binding......................................................................................................108 30.2. Event sequences.......................................................................................................109 30.3. Event types..............................................................................................................109 30.4. Event modifiers........................................................................................................110 30.5. Key names...............................................................................................................111 30.6. Writing your handler: The Event class......................................................................113 30.7. The extra arguments trick..........................................................................................115 30.8. Virtual events...........................................................................................................116 31. Pop-up dialogs....................................................................................................................116 31.1. The tkMessageBox dialogs module..........................................................................116 31.2. The tkFileDialog module.....................................................................................118 31.3. The tkColorChooser module.................................................................................119

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

侠之大者为国为民

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值