今天看到了GUI编程,书上推荐用wxPython,去官网上看了看,发现Windows的最高支持到2.7,我用的是3.4版本,咋办,用自带的库--Tkinter呗,它是Python的默认GUI库,几乎是个标准库,也是受广大开发者喜爱的。

    Tkinter有很多组件(其实也不多,十来个),今天主要用标签、按钮、进度条,写一个字体随进度条改变大小并且可以写文件的小程序,其他组件用法看文档就行,以前用C#写过winform的应该有经验。直接上代码:

#---coding:utf-8---
from tkinter import * #导包
def resize(ev=None):
    '根据进度条调整字体大小'
    label.config(font='Helvetica -%d bold' %scale.get())

def writefile():
    '写文件'
    try:
        f = open(r'd:\hello.txt','w')
        f.write('hello,world!')
    except Exception as e:
        print(e)
    finally:
        f.close()

top = Tk()#新建一个窗口
top.geometry('400x300')#指定窗口大小
top.title('GUI_test')

label = Label(top,text='Hello,World!',font='Helvetica -12 bold')#随进度条变化的标签,刚开始学当然用hello,world
label.pack(fill=Y,expand=1)

scale = Scale(top,from_=10,to=50,orient=HORIZONTAL,command=resize)#进度条,个人认为command作用和绑定差不多
scale.set(12)#设初值
scale.pack(fill=X,expand=1)

write = Button(top,text="Write",command=writefile)
write.pack()

quit = Button(top,text="Quit",command=top.quit,activeforeground='White',
              activebackground='red')
quit.pack()

mainloop()#调用该函数运行程序

     注意到每配置好一个组件,后面都有一句X.pack(***),最后的mainloop()是用来启动你编的GUI程序,那pack()是什么鬼,查一下文档,有这么一段话

The packer is one of Tk’s geometry-management mechanisms. Geometry managers are used to specify the relative positioning of the positioning of widgets within their container - their mutual master. In contrast to the more cumbersome placer (which is used less commonly, and we do not cover here), the packer takes qualitative relationship specification - above, to the left of, filling, etc - and works everything out to determine the exact placement coordinates for you.The pack() method can be called with keyword-option/value pairs that control where the widget is to appear within its container, and how it is to behave when the main application window is resized.意思大概就是说packer这哥们是管理和显示组件的,pack()方法用来指定组件的显示。看下运行效果:

   

    打开D盘hello.txt,发现了我们写的hello,world!这样简单的GUI编程完成了,还用到了一点文件编程的知识,和预期效果一样,得赶快学习网络部分了,不然毕设进度得耽搁了。

posted on 2016-04-08 17:57  seven_clear  阅读(577)  评论(0编辑  收藏  举报