美文网首页思科DevNet生活不易 我用python
Python自带的Tkinter写GUI小程序

Python自带的Tkinter写GUI小程序

作者: AwesomeAshe | 来源:发表于2016-07-31 13:21 被阅读1961次

学了一点点python基础语法,就斗胆用它加上一些文件读写的module,写了几个文件处理的程序;
但是需求又说:写个简单的GUI吧,用起来方便。

目标:GUI实现

  • 点击选择文件按钮弹出windows的文件管理器,选取所需要的文件/文件夹
  • 将上述的路径显示出来
  • 点击运行按钮,运行文件处理程序
效果图

工具:选择了python自带的tkinter

参考资料:
http://www.tutorialspoint.com/python/python_gui_programming.htm
简直是最全面的资料!

简单介绍一下最关键的部分:
首先要有一个基本的框架,我们在这个框架里面添加其他的框架:
root = Tk() #base window
这个root就是主框架名

框架布局

然后我们计划一下,程序有哪几个部分,因为要设计布局,而tkinter非常简单,只能定义上下左右4个方向;我们定义两个主要的部分,左边和右边:

buttonfrm = Frame(root)         #'button frame' is in Root window
buttonfrm.pack()

textframe = Frame(root)       #text frame in Root window
textframe.pack(side=LEFT)

textframe 和 buttonframe 是两个副框架名

然后我们在里面去定义组件。

语法:#

因为上面那个连接是最全面的,我就不多说了,尽量参考原文档。

按钮:

B = Tkinter.Button(top, text ="Hello", command = function)

字符框:

可实时更新哦(用下面的set函数)

var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()

示例:

import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
  tkMessageBox.showinfo( "Hello Python", "Hello World")
  B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
  B.pack()
top.mainloop()
示例效果

python 代码:

import tkinter
from tkinter import *

global s

s='sssss'
def func1():
    s='fucked!'
    outputtext.set(s)

root = Tk()                     #base window
buttonfrm = Frame(root)         #'button frame' is in Root window
buttonfrm.pack()

textframe = Frame(root)       #text frame in Root window
textframe.pack(side=LEFT)

btnfrm=Frame(root)
btnfrm.pack(side=BOTTOM)

inputbutton = Button(buttonfrm, text="Input",command=func1)       #command = helloCallBack
inputbutton.pack()

outputbutton = Button(buttonfrm, text="Output")
outputbutton.pack()




inputtext=StringVar()
inputmsg=Label(textframe,textvariable=inputtext, relief=RAISED)
inputtext.set(s)
inputmsg.pack()

s='changed!'
outputtext=StringVar()
outputmsg=Label(textframe,textvariable=outputtext, relief=RAISED)
outputtext.set(s)
outputmsg.pack()



#run & exit button
runbutton = Button(btnfrm, text="RUN!",fg='red')
runbutton.pack()

exitbutton = Button(btnfrm, text="EXIT!",command=root.quit)
exitbutton.pack()

root.mainloop()

相关文章

网友评论

    本文标题:Python自带的Tkinter写GUI小程序

    本文链接:https://www.haomeiwen.com/subject/itotsttx.html