Python tkinter模块中类继承的三种方式分析

yipeiwu_com6年前Python基础

本文实例讲述了Python tkinter模块中类继承的三种方式。分享给大家供大家参考,具体如下:

tkinter class继承有三种方式。

提醒注意这几种继承的运行方式

一、继承 object

1.铺tk.Frame给parent:

说明:

self.rootframe = tk.Frame(parent)
tk.Label(self.rootframe)

import tkinter as tk
class MyApp(object):
  def __init__(self, parent):
    self.rootframe = tk.Frame(parent)
    self.rootframe.pack()
    self.setupUI()
  def setupUI(self):
    tk.Label(self.rootframe, text='标签').pack()
if __name__ == '__main__':
  root = tk.Tk()
  MyApp(root) # 注意这句
  root.mainloop()

2.直接使用root

说明:

self.root = parent
tk.Label(self.root)

import tkinter as tk
class MyApp(object):
  def __init__(self, parent, **kwargs):
    self.root = parent
    self.root.config(**kwargs)
    self.setupUI()
  def setupUI(self):
    tk.Label(self.root, text = '标签').pack()
if __name__ == '__main__':
  root = tk.Tk()
  app = test(root)
  root.mainloop()

二、继承 tk.Tk

import tkinter as tk
class MyApp(tk.Tk):
  def __init__(self):
    super().__init__()
    self.setupUI()
  def setupUI(self):
    tk.Label(self, text='标签').pack()
if __name__ == '__main__':
  MyApp().mainloop()

三、继承 tk.Frame

分两种情况

1.有parent

import tkinter as tk
class MyApp(tk.Frame):
  def __init__(self, parent=None):
    super().__init__(parent)
    self.pack()
    self.setupUI()
  def setupUI(self):
    tk.Label(self, text='标签').pack()
if __name__ == '__main__':
  MyApp(tk.Tk()).mainloop()
  #MyApp().mainloop() # 也可以这样

注意: self.pack()

2.没有parent

import tkinter as tk
class MyApp(tk.Frame):
  def __init__(self):
    super().__init__()
    self.pack()
    self.setupUI()
  def setupUI(self):
    tk.Label(self, text='标签').pack()
if __name__ == '__main__': 
  MyApp().mainloop()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python遍历字典方式就实例详解

这篇文章主要介绍了Python遍历字典方式就实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 “ 记录遍历字典的几种方式”...

Python实现的数据结构与算法之队列详解

Python实现的数据结构与算法之队列详解

本文实例讲述了Python实现的数据结构与算法之队列。分享给大家供大家参考。具体分析如下: 一、概述 队列(Queue)是一种先进先出(FIFO)的线性数据结构,插入操作在队尾(rear...

python仿evething的文件搜索器实例代码

python仿evething的文件搜索器实例代码

今天看到everything搜索速度秒杀windows自带的文件管理器,所以特地模仿everything实现了文件搜索以及打开对应文件的功能,首先来一张搜索对比图。 这是evething...

django框架单表操作之增删改实例分析

django框架单表操作之增删改实例分析

本文实例讲述了django框架单表操作之增删改。分享给大家供大家参考,具体如下: 首先找到操作的首页面 代码如下 <!DOCTYPE html> <html lan...

Python中的MongoDB基本操作:连接、查询实例

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可护展的高性能数据存储解决方案。它的特点是高性能、易部署、易使用,存储数据非常方便。 MongoDB...