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实现狄克斯特拉算法

一、简介 是从一个顶点到其余各顶点的最短路径算法,解决的是有向图中最短路径问题。迪杰斯特拉算法主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止 二、步骤 (1) 找出“最便宜”的...

python提取页面内url列表的方法

本文实例讲述了python提取页面内url列表的方法。分享给大家供大家参考。具体实现方法如下: from bs4 import BeautifulSoup import time,r...

如何使用七牛Python SDK写一个同步脚本及使用教程

如何使用七牛Python SDK写一个同步脚本及使用教程

七牛云存储的 Python 语言版本 SDK(本文以下称 Python-SDK)是对七牛云存储API协议的一层封装,以提供一套对于 Python 开发者而言简单易用的开发工具。Pytho...

python字典DICT类型合并详解

python字典DICT类型合并详解

本文为大家分享了python字典DICT类型合并的方法,供大家参考,具体内容如下 我要的字典的键值有些是数据库中表的字段名, 但是有些却不是, 我需要把它们整合到一起, 因此有些这篇文章...

Python strip lstrip rstrip使用方法

    注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如: theString = 'saaaay&nb...