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设计】。

相关文章

Python编写的com组件发生R6034错误的原因与解决办法

解决该问题的方法可以为调用本程序的exe文件建立一个合适的manifest文件,指定正确的msvcr90.dll版本即可,具体可参照/post/35219.htm ps:可以使用mt.e...

python3 flask实现文件上传功能

本文实例为大家分享了python3-flask文件上传操作的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import os import uu...

python实现二叉树的遍历

python实现二叉树的遍历

本文实例为大家分享了python实现二叉树的遍历具体代码,供大家参考,具体内容如下 代码: # -*- coding: gb2312 -*- class Queue(obje...

python 统计文件中的字符串数目示例

题目: 一个txt文件中已知数据格式为: C4D C4D/maya C4D C4D/su C4D/max/AE 统计每个字段出现的次数,比如C4D、maya 先读取文件,将文件中的数据抽...

Python 生成一个从0到n个数字的列表4种方法小结

我就废话不多说了,直接上代码吧! 第一种 def test1(): l = [] for i in range(1000): l = l + [i] 第二种(app...