Python Tkinter实现的WIN7电脑端共享WIFI热点(二)

前面写了一个简单的管理电脑创建的WIFI热点的工具,整体比较简单,只是由一个图片,和2个button,还有一个MessageBox组成,这两天又完善了下,主要更新了以下几个方面:

1.使用类来编写代码(由于自己基本还是面向过程思想,有必要学习下类的基本写法)

2.将版本1中的MessageBox改为由ListBox和Scrollbar组成的frame,这样信息可以一直显示在listbox里面。

3.增加了菜单栏,并添加了一些子菜单。

4.程序窗口固定,退出需用户确认。


下面是源代码:

# -*- coding: utf-8 -*-
#author: Cullen

#import the needed module
from Tkinter import *
import tkFont
import tkMessageBox
import os
from PIL import ImageTk, Image

def close_window(window):
    """give prompt when user close the window"""
    if tkMessageBox.askyesno("QUIT", "Close the Window(Yes/No)", icon="question"):
        window.destroy() 
    
def manage_wifi(how, message_frame):
    """this function will open/close the wifi network accoring the arguments:
        how=1(open the network) how=2(close the network),
        message_frame(the frame which the message display"""
    
    open_wifi_cmd = "netsh wlan start hostednetwork"
    close_wifi_cmd = "netsh wlan stop hostednetwork"
    
    if how == 1:
        cmd = open_wifi_cmd
    else:
        cmd = close_wifi_cmd

    result = os.system(cmd)
    if result != 0:
        if how == 1:
            message_frame.listbox_insert("请检查无线网卡是否打开,设置是否正确")
        else:
            message_frame.listbox_insert("关闭WIFI失败!")
    else:
        if how == 1:
            message_frame.listbox_insert("WIFI已打开")
        else:
            message_frame.listbox_insert("WIFI已关闭")

class ShowMessageFrame():
    """will create a frame contanis a listbox and scrollbar"""
    
    def __init__(self):
        self.frame = Frame()
        self.message_ft = tkFont.Font(family="Arial", size=10)
        self.scrollbar = Scrollbar(self.frame, orient=VERTICAL)
        self.listbox = Listbox(self.frame, bg="grey", selectbackground="blue",
                               selectmode="extended", font=self.message_ft, width=20)
        self.scrollbar.config(command=self.listbox.yview)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.listbox.config(yscrollcommand=self.scrollbar.set)
        self.listbox.pack(side=LEFT, fill=BOTH, expand=1)

        self.listbox_insert("Welcome to WIFI!")

    def listbox_insert(self, args):
        self.listbox.insert(END, args)

class MyMenu():
    """Create the Menu for Window"""
    message_status = 1
    def __init__(self, root):
        
        self.menubar = Menu(root)
        self.optionmenu = Menu(self.menubar, tearoff=1)
        self.optionmenu.add_command(label='Show Message', command=lambda : self.show_messagebox(root))
        self.optionmenu.add_command(label='Hide Message', command=lambda : self.hide_messagebox(root))
        self.optionmenu.add_separator()
        self.optionmenu.add_command(label='Exit', command=lambda : close_window(root))
        self.menubar.add_cascade(label='Options', menu=self.optionmenu)

        self.helpmenu = Menu(self.menubar, tearoff=1)
        self.helpmenu.add_command(label='About', command=self.show_info)
        self.menubar.add_cascade(label='Help', menu=self.helpmenu)

        self.frame = ''

    def hide_messagebox(self, root):
        """will hide the message listbox and scrollbar"""
        if self.message_status == 1:
            self.frame = root.grid_slaves(2,0)[0]
            root.grid_slaves(2,0)[0].grid_remove()
            self.__class__.message_status = 0

    def show_messagebox(self, root):
        if self.message_status == 0 and self.frame != '':
            #print root.grid_slaves(2,0)
            
            self.frame.grid(row=2, columnspan=2, pady=5, sticky=S+N+E+W)
            self.__class__.message_status = 1
            self.frame = ''
        
        
    def show_info(self):
        """show the software info""" 
        tkMessageBox.showinfo("About",
                              """
                    WIFI 热点助手
        ------------------------------------------
                version: 1.0
                author: Cullen
                Email:  [email protected]
        ------------------------------------------""" )
         
class MyWindow():
    """ create the main window which include the image and two button(bounded the appropriate function"""
    
    def __init__(self):
        self.root = Tk()
        self.root.title("WIFI热点助手");
        self.root.resizable(0,0)

        #create menu
        my_menu = MyMenu(self.root)
        self.root.config(menu=my_menu.menubar)

        #font and image
        self.button_ft = tkFont.Font(family="Arial", size=10, weight=tkFont.BOLD)
        self.image = Image.open("wifi.jpg")
        self.bm = ImageTk.PhotoImage(self.image)
        
        self.label = Label(self.root, image=self.bm)
        self.label.grid(row=0, columnspan=2)

        #create button
        self.open_button = Button(self.root, text="OPEN", font=self.button_ft, pady=10,
                                  width=10, borderwidth=2, bg="#F3E9CC", command=lambda : manage_wifi(1, message_frame))
        self.open_button.grid(row=1, column=0)

        self.close_button = Button(self.root, text="CLOSE", font=self.button_ft, pady=10,
                                   width=10, borderwidth=2, bg="#F3E9CC", command=lambda : manage_wifi(0, message_frame))
        self.close_button.grid(row=1, column=1)

        #create frame which include listbox and scrollbar
        message_frame = ShowMessageFrame()
        message_frame.frame.grid(row=2, columnspan=2, pady=5, sticky=S+N+E+W)
        #message_frame.frame.grid_forget()

        #prompt when user close the window
        self.root.protocol('WM_DELETE_WINDOW', lambda : close_window(self.root))
        self.root.mainloop()

if __name__ == '__main__':
    #main()
    my_window = MyWindow()


下面是运行后的结果:


点击open/close按钮会打开或关闭WIFI,并在下面的消息框内输出提示信息,右侧的滚动条可以进行上下移动,如下图所示:

Python Tkinter实现的WIN7电脑端共享WIFI热点(二)_第1张图片


菜单栏里的help会显示一些信息:



Option里的Hide Message会隐藏下面的消息框,而点击Show Message则又会重新显示出来:

Python Tkinter实现的WIN7电脑端共享WIFI热点(二)_第2张图片


而点击Exit子菜单和右上角的关闭图标,都会弹出对话框,让用户进行确认:



下面是源代码,运行环境为python2.7,不足之处请指出,谢谢!

点击打开链接


你可能感兴趣的:(python,GUI,实例,tkinter)