104.md 21.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
# wxPython 中的事件

> 原文: [http://zetcode.com/wxpython/events/](http://zetcode.com/wxpython/events/)

事件是每个 GUI 应用程序不可或缺的一部分。 所有 GUI 应用程序都是事件驱动的。 应用程序会对在其生命周期内生成的不同事件类型做出反应。 事件主要由应用程序的用户生成。 但是它们也可以通过其他方式生成。 例如 Internet 连接,窗口管理器或计时器。 因此,当我们调用`MainLoop()`方法时,我们的应用程序将等待事件生成。 当我们退出应用程序时,`MainLoop()`方法结束。

## 定义

_ 事件 _ 是来自底层框架(通常是 GUI 工具箱)的应用程序级信息。 _ 事件循环 _ 是一种程序结构,用于等待并调度程序中的事件或消息。 事件循环反复查找要处理的事件。 _ 调度程序 _ 是将事件映射到 _ 事件处理程序 _ 的过程。 事件处理程序是对事件做出反应的方法。

_ 事件对象 _ 是与事件关联的对象。 通常是一个窗口。 _ 事件类型 _ 是已生成的唯一事件。 _ 事件绑定器 _ 是将事件类型与事件处理程序绑定在一起的对象。

## wxPython wx.EVT_MOVE 示例

在下面的示例中,我们对`wx.MoveEvent`事件做出反应。 当我们将窗口移到新位置时会生成该事件。 此事件的事件绑定器为`wx.EVT_MOVE`

`simple_event.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

This is a wx.MoveEvent event demostration.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        wx.StaticText(self, label='x:', pos=(10,10))
        wx.StaticText(self, label='y:', pos=(10,30))

        self.st1 = wx.StaticText(self, label='', pos=(30, 10))
        self.st2 = wx.StaticText(self, label='', pos=(30, 30))

        self.Bind(wx.EVT_MOVE, self.OnMove)

        self.SetSize((350, 250))
        self.SetTitle('Move event')
        self.Centre()

    def OnMove(self, e):

        x, y = e.GetPosition()
        self.st1.SetLabel(str(x))
        self.st2.SetLabel(str(y))

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main() 

```

该示例显示窗口的当前位置。

```
self.Bind(wx.EVT_MOVE, self.OnMove)

```

在这里,我们将`wx.EVT_MOVE`事件绑定器绑定到`OnMove()`方法。

```
def OnMove(self, e):

    x, y = e.GetPosition()
    self.st1.SetLabel(str(x))
    self.st2.SetLabel(str(y))

```

`OnMove()`方法中的事件参数是特定于特定事件类型的对象。 在我们的例子中,它是`wx.MoveEvent`类的实例。 该对象保存有关事件的信息。 例如事件对象或窗口的位置。 在我们的例子中,事件对象是`wx.Frame`小部件。 我们可以通过调用事件的`GetPosition()`方法找出当前位置。

![Move event](img/cecccdda7bf15a6d573e1dd0225e96b0.jpg)

Figure: Move event

## wxPython 事件绑定

在 wxPython 中使用事件的三个​​步骤是:

*   标识事件绑定程序名称:`wx.EVT_SIZE``wx.EVT_CLOSE`等。
*   创建一个事件处理程序。 生成事件时将调用此方法。
*   将事件绑定到事件处理程序。

在 wxPython 中,我们说将方法绑定到事件。 有时会使用单词钩子。 您可以通过调用`Bind()`方法来绑定事件。 该方法具有以下参数:

```
Bind(event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)

```

`event`是 EVT_ *对象之一。 它指定事件的类型。 `handler`是要调用的对象。 换句话说,它是程序员绑定到事件的一种方法。 当我们要区分相同事件类型和不同小部件时,使用`source`参数。 当我们有多个按钮,菜单项等时,将使用`id`参数。`id`用于在它们之间进行区分。 当需要将处理程序绑定到 ID 范围时,例如`EVT_MENU_RANGE`,可以使用`id2`

注意,方法`Bind()`在类`EvtHandler`中定义。 它是`wx.Window`继承的类。 `wx.Window`是 wxPython 中大多数小部件的基类。 还有一个相反的过程。 如果要从事件中取消绑定方法,请调用`Unbind()`方法。 它具有与上述相同的参数。

## 否决事件

有时我们需要停止处理事件。 为此,我们称方法`Veto()`

`event_veto.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import wx

"""
ZetCode wxPython tutorial

In this example we veto an event.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        self.SetTitle('Event veto')
        self.Centre()

    def OnCloseWindow(self, e):

        dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question',
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        ret = dial.ShowModal()

        if ret == wx.ID_YES:
            self.Destroy()
        else:
            e.Veto()

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在我们的示例中,我们处理`wx.CloseEvent`。 当我们单击标题栏上的 X 按钮,按 <kbd>Alt</kbd> + <kbd>F4</kbd> 或从系统菜单中选择关闭时,将称为此事件。 在许多应用程序中,如果要进行一些更改,我们希望防止意外关闭窗口。 为此,我们必须绑定`wx.EVT_CLOSE`事件绑定器。

```
dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question',
    wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

ret = dial.ShowModal()

```

在处理 close 事件期间,我们显示一个消息对话框。

```
if ret == wx.ID_YES:
    self.Destroy()
else:
    event.Veto()

```

根据对话框的返回值,我们销毁窗口或否决事件。 注意,要关闭窗口,我们必须调用`Destroy()`方法。 通过调用`Close()`方法,我们将陷入无尽的循环。

## wxPython 事件传播

事件有两种类型:基本事件和命令事件。 它们的传播方式不同。 事件传播是事件从子窗口小部件到父窗口小部件和祖父窗口小部件的传播。 基本事件不会传播。 命令事件确实传播。 例如,`wx.CloseEvent`是一个基本事件。 此事件传播到父窗口小部件没有任何意义。

默认情况下,在事件处理程序中捕获的事件停止传播。 为了继续传播,我们调用`Skip()`方法。

`event_propagation.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

This example demonstrates event propagation.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class MyPanel(wx.Panel):

    def __init__(self, *args, **kw):
        super(MyPanel, self).__init__(*args, **kw)

        self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)

    def OnButtonClicked(self, e):

        print('event reached panel class')
        e.Skip()

class MyButton(wx.Button):

    def __init__(self, *args, **kw):
        super(MyButton, self).__init__(*args, **kw)

        self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)

    def OnButtonClicked(self, e):

        print('event reached button class')
        e.Skip()

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        mpnl = MyPanel(self)

        MyButton(mpnl, label='Ok', pos=(15, 15))

        self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)

        self.SetTitle('Propagate event')
        self.Centre()

    def OnButtonClicked(self, e):

        print('event reached frame class')
        e.Skip()

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在我们的示例中,面板上有一个按钮。 面板放置在框架小部件中。 我们为所有小部件定义一个处理程序。

```
def OnButtonClicked(self, e):

    print('event reached button class')
    e.Skip()

```

我们在自定义按钮类中处理按钮单击事件。 `Skip()`方法将事件进一步传播到面板类。

尝试省略一些`Skip()`方法,看看会发生什么。

## 窗口标识符

窗口标识符是在事件系统中唯一确定窗口标识的整数。 有三种创建窗口 ID 的方法。

*   让系统自动创建一个 ID
*   使用标准标识符
*   创建自己的 ID

```
wx.Button(parent, -1)
wx.Button(parent, wx.ID_ANY)

```

如果为 id 参数提供-1 或`wx.ID_ANY`,则让 wxPython 自动为我们创建一个 id。 自动创建的 ID 始终为负,而用户指定的 ID 必须始终为正。 当我们不需要更改窗口小部件状态时,通常使用此选项。 例如,静态文本在应用程序的生命周期内将永远不会更改。 如果需要,我们仍然可以获取 ID。 有一种确定 ID 的方法`GetId()`

`default_ids.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we use automatic ids
with wx.ID_ANY.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        pnl = wx.Panel(self)
        exitButton = wx.Button(pnl, wx.ID_ANY, 'Exit', (10, 10))

        self.Bind(wx.EVT_BUTTON,  self.OnExit, id=exitButton.GetId())

        self.SetTitle("Automatic ids")
        self.Centre()

    def OnExit(self, event):

        self.Close()

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在此示例中,我们不在乎实际的 id 值。

```
self.Bind(wx.EVT_BUTTON,  self.OnExit, id=exitButton.GetId())

```

我们通过调用`GetId()`方法来获取自动生成的 ID。

建议使用标准标识符。 标识符可以在某些平台上提供一些标准的图形或行为。

## wxPython 标准 ID

wxPython 包含一些标准 ID,例如`wx.ID_SAVE``wx.ID_NEW`

`standard_ids.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we create buttons with standard ids.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        pnl = wx.Panel(self)
        grid = wx.GridSizer(3, 2)

        grid.AddMany([(wx.Button(pnl, wx.ID_CANCEL), 0, wx.TOP | wx.LEFT, 9),
            (wx.Button(pnl, wx.ID_DELETE), 0, wx.TOP, 9),
            (wx.Button(pnl, wx.ID_SAVE), 0, wx.LEFT, 9),
            (wx.Button(pnl, wx.ID_EXIT)),
            (wx.Button(pnl, wx.ID_STOP), 0, wx.LEFT, 9),
            (wx.Button(pnl, wx.ID_NEW))])

        self.Bind(wx.EVT_BUTTON, self.OnQuitApp, id=wx.ID_EXIT)

        pnl.SetSizer(grid)

        self.SetTitle("Standard ids")
        self.Centre()

    def OnQuitApp(self, event):

        self.Close()

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在我们的示例中,我们在按钮上使用标准标识符。 在 Linux 上,按钮带有图标。

```
grid.AddMany([(wx.Button(pnl, wx.ID_CANCEL), 0, wx.TOP | wx.LEFT, 9),
    (wx.Button(pnl, wx.ID_DELETE), 0, wx.TOP, 9),
    (wx.Button(pnl, wx.ID_SAVE), 0, wx.LEFT, 9),
    (wx.Button(pnl, wx.ID_EXIT)),
    (wx.Button(pnl, wx.ID_STOP), 0, wx.LEFT, 9),
    (wx.Button(pnl, wx.ID_NEW))])

```

我们向网格大小调整器添加六个按钮。 `wx.ID_CANCEL``wx.ID_DELETE``wx.ID_SAVE``wx.ID_EXIT``wx.ID_STOP``wx.ID_NEW`是标准标识符。

```
self.Bind(wx.EVT_BUTTON, self.OnQuitApp, id=wx.ID_EXIT)

```

我们将按钮单击事件绑定到`OnQuitApp()`事件处理程序。 id 参数用于区分按钮。 我们唯一地标识事件的来源。

![Standard identifiers](img/2970522f1f2eb32db73c05d5e0c41244.jpg)

Figure: Standard identifiers

## 自定义事件 ID

最后一个选择是使用自己的标识符。 我们定义了自己的全局 ID。

`custom_ids.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we use custom event ids.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

ID_MENU_NEW = wx.NewId()
ID_MENU_OPEN = wx.NewId()
ID_MENU_SAVE = wx.NewId()

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        self.CreateMenuBar()
        self.CreateStatusBar()

        self.SetSize((350, 250))
        self.SetTitle('Custom ids')
        self.Centre()

    def CreateMenuBar(self):

        mb = wx.MenuBar()

        fMenu = wx.Menu()
        fMenu.Append(ID_MENU_NEW, 'New')
        fMenu.Append(ID_MENU_OPEN, 'Open')
        fMenu.Append(ID_MENU_SAVE, 'Save')

        mb.Append(fMenu, '&File')
        self.SetMenuBar(mb)

        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_NEW)
        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_OPEN)
        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_SAVE)

    def DisplayMessage(self, e):

        sb = self.GetStatusBar()

        eid = e.GetId()

        if eid == ID_MENU_NEW:
            msg = 'New menu item selected'
        elif eid == ID_MENU_OPEN:
            msg = 'Open menu item selected'
        elif eid == ID_MENU_SAVE:
            msg = 'Save menu item selected'

        sb.SetStatusText(msg)

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main() 

```

在代码示例中,我们创建一个包含三个菜单项的菜单。 此菜单项的 ID 是全局创建的。

```
ID_MENU_NEW = wx.NewId()
ID_MENU_OPEN = wx.NewId()
ID_MENU_SAVE = wx.NewId()

```

`wx.NewId()`方法创建一个新的唯一 ID。

```
self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_NEW)
self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_OPEN)
self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_SAVE) 

```

这三个菜单项均由其唯一 ID 标识。

```
eid = e.GetId()

if eid == ID_MENU_NEW:
    msg = 'New menu item selected'
elif eid == ID_MENU_OPEN:
    msg = 'Open menu item selected'
elif eid == ID_MENU_SAVE:
    msg = 'Save menu item selected'

```

从事件对象中,我们检索 ID。 根据 id 值,我们准备消息,该消息显示在应用程序的状态栏中。

## wx.PaintEvent

重绘窗口时会生成一次绘制事件。 当我们调整窗口大小或最大化窗口时,会发生这种情况。 绘画事件也可以通过编程方式生成。 例如,当我们调用`SetLabel()`方法来更改`wx.StaticText`小部件时。 请注意,当我们最小化窗口时,不会生成任何绘制事件。

`paint_event.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we count paint events.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        self.count = 0
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.SetTitle('Paint events')
        self.SetSize((350, 250))
        self.Centre()

    def OnPaint(self, e):

        self.count += 1
        dc = wx.PaintDC(self)
        text = "Number of paint events: {0}".format(self.count)
        dc.DrawText(text, 20, 20)

def main():

    app = wx.App()
    ex  = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在我们的示例中,我们计算绘制事件的数量并在窗口上绘制当前生成的事件的数量。

```
self.Bind(wx.EVT_PAINT, self.OnPaint)

```

我们将`EVT_PAINT`事件绑定到`OnPaint()`方法。

```
def OnPaint(self, e):

    self.count += 1
    dc = wx.PaintDC(self)
    text = "Number of paint events: {0}".format(self.count)
    dc.DrawText(text, 20, 20)

```

`OnPaint()`事件内部,我们使用`DrawText()`方法增加了计数器绘制窗口上绘画事件的数量。

## wx.FocusEvent

焦点指示应用程序中当前选择的窗口小部件。 从键盘输入或从剪贴板粘贴的文本将发送到具有焦点的小部件。 有两种与焦点有关的事件类型。 `wx.EVT_SET_FOCUS`事件,当窗口小部件获得焦点时生成。 小部件失去焦点时,将生成`wx.EVT_KILL_FOCUS`。 通常,通过单击或使用键盘键来更改焦点,通常是<kbd>选项卡</kbd><kbd>Shift</kbd> + <kbd>选项卡</kbd>

`focus_event.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we work with wx.FocusEvent.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class MyWindow(wx.Panel):

    def __init__(self, parent):
        super(MyWindow, self).__init__(parent)

        self.color = '#b3b3b3'

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

    def OnPaint(self, e):

        dc = wx.PaintDC(self)

        dc.SetPen(wx.Pen(self.color))
        x, y = self.GetSize()
        dc.DrawRectangle(0, 0, x, y)

    def OnSize(self, e):

        self.Refresh()

    def OnSetFocus(self, e):

        self.color = '#ff0000'
        self.Refresh()

    def OnKillFocus(self, e):

        self.color = '#b3b3b3'
        self.Refresh()

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        grid = wx.GridSizer(2, 2, 10, 10)
        grid.AddMany([(MyWindow(self), 0, wx.EXPAND|wx.TOP|wx.LEFT, 9),
            (MyWindow(self), 0, wx.EXPAND|wx.TOP|wx.RIGHT, 9),
            (MyWindow(self), 0, wx.EXPAND|wx.BOTTOM|wx.LEFT, 9),
            (MyWindow(self), 0, wx.EXPAND|wx.BOTTOM|wx.RIGHT, 9)])

        self.SetSizer(grid)

        self.SetSize((350, 250))
        self.SetTitle('Focus event')
        self.Centre()

    def OnMove(self, e):

        print(e.GetEventObject())
        x, y = e.GetPosition()
        self.st1.SetLabel(str(x))
        self.st2.SetLabel(str(y))

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在我们的示例中,我们有四个面板。 重点突出显示的面板。

```
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

```

我们将两个焦点事件绑定到事件处理程序。

```
def OnPaint(self, e):

    dc = wx.PaintDC(self)

    dc.SetPen(wx.Pen(self.color))
    x, y = self.GetSize()
    dc.DrawRectangle(0, 0, x, y)

```

`OnPaint()`方法中,我们在窗口上绘制。 轮廓线的颜色取决于窗口是否具有焦点。 聚焦窗口的轮廓以红色绘制。

```
def OnSetFocus(self, e):

    self.color = '#ff0000'
    self.Refresh()

```

`OnSetFocus()`方法中,我们将`self.color`变量设置为红色。 我们刷新框架窗口,这将为其所有子窗口小部件生成一个绘制事件。 重新绘制了窗口,焦点所在的窗口的轮廓线有了新的颜色。

```
def OnKillFocus(self, e):

    self.color = '#b3b3b3'
    self.Refresh()

```

当窗口失去焦点时,将调用`OnKillFocus()`方法。 我们更改颜色值并刷新。

![Focus event](img/80109de59ce12718302d77da19c1dc2a.jpg)

Figure: Focus event

## wx.KeyEvent

当我们按下键盘上的一个键时,会生成一个`wx.KeyEvent`。 此事件发送到当前具有焦点的窗口小部件。 共有三种不同的密钥处理程序:

*   wx.EVT_KEY_DOWN
*   wx.EVT_KEY_UP
*   wx.EVT_CHAR

常见的请求是在按下 <kbd>Esc</kbd> 键时关闭应用程序。

`key_event.py`

```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ZetCode wxPython tutorial

In this example we work with wx.KeyEvent.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):

        pnl = wx.Panel(self)
        pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        pnl.SetFocus()

        self.SetSize((350, 250))
        self.SetTitle('Key event')
        self.Centre()

    def OnKeyDown(self, e):

        key = e.GetKeyCode()

        if key == wx.WXK_ESCAPE:

            ret  = wx.MessageBox('Are you sure to quit?', 'Question',
                wx.YES_NO | wx.NO_DEFAULT, self)

            if ret == wx.YES:
                self.Close()

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

```

在此示例中,我们处理 <kbd>Esc</kbd> 按键。 显示一个消息框,以确认应用程序的终止。

```
pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

```

我们将事件处理程序绑定到`wx.EVT_KEY_DOWN`事件。

```
key = e.GetKeyCode()

```

在这里,我们获得了按下的键的键控代码。

```
if key == wx.WXK_ESCAPE:

```

我们检查密钥。 <kbd>Esc</kbd> 键具有`wx.WXK_ESCAPE`代码。

在本章中,我们讨论了 wxPython 中的事件。