打赏

起源:

研究Python UI编程,我偏喜欢其原生组件,于是学习Tkinter、ttk组件用法。找一计算器开源代码,略加修整,以为备忘。
其界面如图所示:

 

1、源代码(Python 2.7):

# encoding: UTF-8

from Tkinter import *
from ttk import *

calc = Tk()
calc.title('计算器')
calc.resizable(False, False)

buttons = [
    '7', '8', '9', '*', 'C',
    '4', '5', '6', '/', 'Neg',
    '1', '2', '3', '-', '$',
    '0', '.', '=', '+', '@']

# set up GUI
row = 1
col = 0
style = Style()
style.configure('BW.TButton', padding=12)
for i in buttons:
    action = lambda x=i: click_event(x)
    Button(calc, text=i, width=7, command=action, style='BW.TButton') \
        .grid(row=row, column=col, sticky='nesw', )
    col += 1
    if col > 4:
        col = 0
        row += 1

display = Entry(calc, width=60)
display.grid(row=0, column=0, columnspan=5)

calc.update()
w = calc.winfo_reqwidth()
h = calc.winfo_reqheight()
s_w = calc.winfo_screenwidth()
s_h = calc.winfo_screenheight()
calc.geometry('%dx%d+%d+%d' % (w, h, (s_w - w) / 2, (s_h - h) / 2))

display.focus_set()

def click_event(key):
    # = -> calculate results
    if key == '=':
        # safeguard against integer division
        if '/' in display.get() and '.' not in display.get():
            display.insert(END, '.0')

        # attempt to evaluate results
        try:
            result = eval(display.get())
            display.insert(END, ' = ' + str(result))
        except:
            display.insert(END, '   Error, use only valid chars')

            # C -> clear display
    elif key == 'C':
        display.delete(0, END)


    # $ -> clear display
    elif key == '$':
        display.delete(0, END)
        display.insert(END, '$$$$C.$R.$E.$A.$M.$$$$')


    # @ -> clear display
    elif key == '@':
        display.delete(0, END)
        display.insert(END, 'website')


    # neg -> negate term
    elif key == 'Neg':
        if '=' in display.get():
            display.delete(0, END)
        try:
            if display.get()[0] == '-':
                display.delete(0)
            else:
                display.insert(0, '-')
        except IndexError:
            pass

            # clear display and start new input
    else:
        if '=' in display.get():
            display.delete(0, END)
        display.insert(END, key)


# RUNTIME
calc.mainloop()

 

 

2、生成exe

反复对比py2exe及PyInstaller,发现py2exe在x64位下不能支持生成一个exe文件,而其在x32下,对Tkinter,也不能生成一个文件。

费尽工夫,也只是少生成几个文件 ,甚为不爽:

而用PyInstaller,可生成单一文件 。但验证其启动速度,甚为耗时:

综合对比,Python做UI,实非方便之物,用其胶水语言之长处,足矣!

 

posted on 2017-09-10 12:01  楚人无衣  阅读(1235)  评论(0编辑  收藏  举报