Python的Tkinter点击按钮触发事件的例子

yipeiwu_com6年前Python基础

如果要开发一个比较大的程序,那么应该先把代码封装起来,在面向对象编程中,就是封装成类

先看代码:

import tkinter as tk

class App:
 def __init__(self, root):
  root.title("打招呼测试")
  frame = tk.Frame(root)
  frame.pack()
  self.hi_there = tk.Button(frame, text="打招呼", fg="blue", command=self.say_hi)
  self.hi_there.pack(side=tk.LEFT)
 def say_hi(self):
  print("您刚才通过点击打招呼触发了我:大家好,我是badao!")
root = tk.Tk()
app = App(root)

root.mainloop()

程序跑起来后:

代码解释:

#导入tkinter模块并创建别名tk

import tkinter as tk

class App:

 def __init__(self, root):

  #设置标题

  root.title("打招呼测试")

  #创建一个框架,然后在里面添加一个Button组件

  #框架的作用一般是在复杂的布局中起到将组件分组的作用

  frame = tk.Frame(root)

  #pack()自动调节组件自身尺寸

  frame.pack()

   #创建一个按钮组件,fg是foreground(前景色)

  self.hi_there = tk.Button(frame, text="打招呼", fg="blue", command=self.say_hi)

  #左对齐

  self.hi_there.pack(side=tk.LEFT)



 def say_hi(self):
  print("您刚才通过点击打招呼触发了我:大家好,我是badao!")

#创建一个toplevel的根窗口,并把它作为参数实例化app对象

root = tk.Tk()
app = App(root)

#开始主事件循环

root.mainloop()

以上这篇Python的Tkinter点击按钮触发事件的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Flask SQLAlchemy一对一,一对多的使用方法实践

Flask-SQLAlchemy安装和建表操作请参考这里。 复制代码 代码如下:# Role表class Role(db.Model):    id=db...

Django如何防止定时任务并发浅析

前言 django提供了commands类,允许我们编写命令行脚本,并且可以通过python manage.py拉起。 了解commands 具体django commands如何使用...

python3.x 生成3维随机数组实例

python3.x 生成3维随机数组实例

如下所示: import numpy as np a=np.random.randint(0,10,size=[3,3,3]) print(a) 以上这篇python...

以Flask为例讲解Python的框架的使用方法

以Flask为例讲解Python的框架的使用方法

了解了WSGI框架,我们发现:其实一个Web App,就是写一个WSGI的处理函数,针对每个HTTP请求进行响应。 但是如何处理HTTP请求不是问题,问题是如何处理100个不同的URL。...

Python http接口自动化测试框架实现方法示例

Python http接口自动化测试框架实现方法示例

本文实例讲述了Python http接口自动化测试框架实现方法。分享给大家供大家参考,具体如下: 一、测试需求描述 对服务后台一系列的http接口功能测试。 输入:根据接口描述构造不同的...