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的for和break循环结构中使用else语句的技巧

在Python中的while或者for循环之后还可以有else子句,作用是for循环中if条件一直不满足,则最后就执行else语句。 for i in range(5): if i...

Python中字符串的常见操作技巧总结

本文实例总结了Python中字符串的常见操作技巧。分享给大家供大家参考,具体如下: 反转一个字符串 >>> S = 'abcdefghijklmnop' >&...

详解django自定义中间件处理

中间件是一个钩子框架,它们可以介入 Django 的请求和响应处理过程。 它是一个轻量级、底层的 插件 系统,用于在 全局修改 Django 的输入或输出 。 每个中间件组件负责完成某个...

Python中optparse模块使用浅析

Python中optparse模块使用浅析

最近遇到一个问题,是指定参数来运行某个特定的进程,这很类似Linux中一些命令的参数了,比如ls -a,为什么加上-a选项会响应。optparse模块实现的也是类似的功能,它是为脚本传递...

Python生成器定义与简单用法实例分析

本文实例讲述了Python生成器定义与简单用法。分享给大家供大家参考,具体如下: 一、什么是生成器 在Python中,由于受到内存的限制,列表容量肯定是有限的。例如我们创建一个包含一亿个...