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

yipeiwu_com6年前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 list格式数据excel导出方法

如下所示: # _*_ coding:utf-8 _*_ #----------------------------------------------- # import mod...

Python简直是万能的,这5大主要用途你一定要知道!(推荐)

从2015开始国内就开始慢慢接触Python了,从16年开始Python就已经在国内的热度更高了,目前也可以算的上"全民Python"了。 众所周知小学生的教材里面已经有Python了,...

python学习——内置函数、数据结构、标准库的技巧(推荐)

我作为一名python初学者,为了强化记忆有必要把看过的一些优秀的文章中一些技巧通过notebook的方式练习一次。我认为这么做有几个优点:一来加深印象;二来也可以将学习过的内容保存方便...

python 调用HBase的简单实例

新来的一个工程师不懂HBase,java不熟,python还行,我建议他那可以考虑用HBase的thrift调用,完成目前的工作。 首先,安装thrift 下载thrift,这里,我用的...

Python使用random模块生成随机数操作实例详解

本文实例讲述了Python使用random模块生成随机数操作。分享给大家供大家参考,具体如下: 今天在用Python编写一个小程序时,要用到随机数,于是就在网上查了一下关于Python生...