python3使用tkinter实现ui界面简单实例

yipeiwu_com5年前Python基础


复制代码 代码如下:

import time
import tkinter as tk

class Window:
    def __init__(self, title='nms', width=300, height=120, staFunc=bool, stoFunc=bool):
        self.w = width
        self.h = height
        self.stat = True
        self.staFunc = staFunc
        self.stoFunc = stoFunc
        self.staIco = None
        self.stoIco = None

        self.root = tk.Tk(className=title)

    def center(self):
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int( (ws/2) - (self.w/2) )
        y = int( (hs/2) - (self.h/2) )
        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))

    def packBtn(self):
        self.btnSer = tk.Button(self.root, command=self.event, width=15, height=3)
        self.btnSer.pack(padx=20, side='left')
        btnQuit = tk.Button(self.root, text='关闭窗口', command=self.root.quit, width=15, height=3)
        btnQuit.pack(padx=20, side='right')

    def event(self):
        self.btnSer['state'] = 'disabled'
        if self.stat:
            if self.stoFunc():
                self.btnSer['text'] = '启动服务'
                self.stat = False
                self.root.iconbitmap(self.stoIco)
        else:
            if self.staFunc():
                self.btnSer['text'] = '停止服务'
                self.stat = True
                self.root.iconbitmap(self.staIco)
        self.btnSer['state'] = 'active'

    def loop(self):
        self.root.resizable(False, False)   #禁止修改窗口大小
        self.packBtn()
        self.center()                       #窗口居中
        self.event()
        self.root.mainloop()

########################################################################
def sta():
    print('start.')
    return True
def sto():
    print('stop.')
    return True

if __name__ == '__main__':
    import sys, os

    w = Window(staFunc=sta, stoFunc=sto)
    w.staIco = os.path.join(sys.exec_prefix, 'DLLs\pyc.ico')
    w.stoIco = os.path.join(sys.exec_prefix, 'DLLs\py.ico')
    w.loop()

相关文章

Python函数中参数是传递值还是引用详解

Python函数中参数是传递值还是引用详解

在 C/C++ 中,传值和传引用是函数参数传递的两种方式,在Python中参数是如何传递的?回答这个问题前,不如先来看两段代码。 代码段1: def foo(arg): arg =...

基于python log取对数详解

log()方法返回x的自然对数,对于x>0。 语法 以下是log()方法的语法: import math math.log( x ) 注意:此函数是无法直接访问的,所以我...

Python可变参数用法实例分析

Python可变参数用法实例分析

本文实例讲述了Python可变参数用法。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import m...

对python sklearn one-hot编码详解

one-hot编码的作用 使用one-hot编码,将离散特征的取值扩展到了欧式空间,离散特征的某个取值就对应欧式空间的某个点 将离散特征通过one-hot编码映射到欧式空间,是因为,在回...

对Python Class之间函数的调用关系详解

假设有Class A 和 Class B两个类,Class A中定义了a(),Class B中定义了b(). 现在我想在Class B中调用 Class A中的函数a()。此处介绍三种调...