Introduction to Programming Using Python——第9章 笔记

CHAPTER 9 

GUI PROGRAMMING USING TKINTER

9.1 Introduction

Tkinter (读作 T-K-Inter 是Tk interface的缩略),是Python自带的GUI库。

-----------------------------------------------------------------------------

9.2 Getting Started with Tkinter

LISTING 9.1 SimpleGUI.py

from tkinter import * # Import all definitions from tkinter

window = Tk() # Create a window
label = Label(window, text = "Welcome to Python") # Create a label
button = Button(window, text = "Click Me") # Create a button
label.pack() # Place the label in the window
button.pack() # Place the button in the window

window.mainloop() # Create an event loop

------------------------------------------------------------------------------

9.3 Processing Events

LISTING 9.3 ProcessButtonEventAlternativeCode.py

from tkinter import *

class ProcessButtonEvent:
    def __init__(self):
        window = Tk() # 创建tk类
        btnOK = Button(window, text = "OK",fg = "red", command = self.processOK)
        btnCancel = Button(window, text = "Cancel", bg = "yellow", command = self.processCancel)
        
        btnOK.pack() # Place the OK button in the window
        btnCancel.pack() # Place the Cancel button in the window
        
        window.mainloop() # Create an event loop
    
    def processOK(self):
        print("OK button is clicked")

    def processCancel(self):
        print("Cancel button is clicked")
        
ProcessButtonEvent() # Create an object to invoke __init__method

这段代码,定义了一个class,然后在class的__init__方法里面创建了GUI。函数processOK和函数processCancel都是class中的instance methods。所以class中调用的时候要使用self.processOK和self.processCancel。

使用定义一个class来创建GUI处理事件有两个好处:

  1. class可以将来反复使用。
  2. 所有函数都作为methods的时候,调用和访问函数的时候,作用域都在class内部。

--------------------------------------------

9.4 The Widget Classes


Tkinter提供的Widget Classes

要放置widgets 需要有parent container,所有widgets都有属性可以设置,设置语法如下:

widgetName["propertyName"] = newPropertyValue

btShowOrHide = Button(window, text = "Show", bg = "white") # 创建一个Button widget放置在window中,text属性为Show,bg属性为white
btShowOrHide["text"] = "Hide" # 将text属性改为Hide
btShowOrHide["bg"] = "red" # 将bg属性改为red
btShowOrHide["fg"] = "#AB84F9" # Change fg color to #AB84F9
btShowOrHide["cursor"] = "plus" # Change mouse cursor to plus
btShowOrHide["justify"] = LEFT # Set justify to LEFT 设置对齐方式为左对齐

关于更多属性方法的使用,此书不做介绍,大家可以去查找tkinter参考文档

listing 9.4将介绍 Frame, Button,Checkbutton, Radiobutton, Label, Entry(text field),Message和Text(text area)组件

LISTING 9.4 WidgetsDemo.py


猜你喜欢

转载自blog.csdn.net/seeleday/article/details/80587035