Python窗口Tkinter Button详解与位置调整

Button参数含义:
width: 指定按钮的宽度
height: 指定按钮的高度
默认的button是text类型, width, heigth表示字符个数和行数
button.place(x=50,y=10)

通过下面的代码快速熟悉Button的参数和Place()函数

#!/usr/bin/python
#-*-coding:utf-8 -*-

from tkinter import messagebox
import tkinter as tk

top = tk.Tk()
#这里四个参数分别为:宽、高、左、上
top.geometry("500x300+750+200")

top.title("www.tianqiweiqi.com")

def okCallBack():
    tk.messagebox.askokcancel("title","info")

btnOk = tk.Button(top,
                  width=10,
                  height=1,
                  text='ok',
                  padx=1,
                  pady=1,
                  anchor='w',
                  command = okCallBack)
btnOk.place(x=50,y=10,anchor='w')
btnOk.pack();

top.mainloop();

Button参数含义:

  anchor:   指定按钮上文本的位置;
  background(bg): 指定按钮的背景色;
  bitmap:指定按钮上显示的位图;
  borderwidth(bd): 指定按钮边框的宽度;
  command: 指定按钮消息的回调函数;
  cursor:    指定鼠标移动到按钮上的指针样式;
  font: 指定按钮上文本的字体;
  foreground(fg): 指定按钮的前景色;
  height:  指定按钮的高度;
  image:  指定按钮上显示的图片;
  state:指定按钮的状态(disabled);
  text: 指定按钮上显示的文本;
  width: 指定按钮的宽度
  padx: 设置文本与按钮边框x的距离,还有pady;
  activeforeground:按下时前景色
  textvariable:可变文本,与StringVar等配合着用

注意: 默认的button是text类型, width, heigth表示字符个数和行数

place()函数

这个的几何管理器组织放置在一个特定的位置,在他们的父widget部件.
语法:
widget.place( place_options )
参数含义:

  • anchor : 部件其他选项的确切位置,请参阅:可能是N,E,S,W,东北,西北,东南或西南,罗盘方向指示的widget的角落,双方默认是净重(部件上左上角)
  • bordermode : INSIDE(默认)表示其他选项是指父母的内(忽略父级的边界);以外地方,否则.
  • height, width : 以像素为单位的高度和宽度.
  • relheight, relwidth : 高度和宽度为0.0和1.0之间浮动,父widget的一小部分的高度和宽度.
  • relx, rely : 水平和垂直偏移为0.0和1.0之间浮动,父widget的一小部分的高度和宽度.
  • x, y : 水平和垂直像素偏移.

Place布局 和 各种控件 简单演示

# -*-coding:utf-8-*-
from tkinter import *


class A:

    def __init__(self, master=None):
        self.root = master
        self.root.geometry('800x600+200+200')
        self.root.title('测试')
        # self.root.bind("<Motion>", self.call_back)
        self.frm1 = Frame(self.root)
        self.frm2 = Frame(self.root)
        self.frm3 = Frame(self.root)
        self.createpage()

    def call_back(self, event):
        print('现在的位置是:', event.x_root, event.y_root)

    def createpage(self):
        menu = Menu(self.root)
        self.root.config(menu=menu)

        filemenu = Menu(menu)
        menu.add_cascade(label='测试1', menu=filemenu)
        filemenu.add_command(label='1')
        filemenu.add_command(label='2')
        filemenu.add_command(label='3')

        onemenu = Menu(menu)
        menu.add_cascade(label='测试2', menu=onemenu)
        onemenu.add_command(label='1')
        onemenu.add_command(label='2')
        onemenu.add_command(label='3')

        self.frm1.config(bg='blue', height=500, width=600)
        Label(self.frm1, text='frm1').place(in_=self.frm1, anchor=NW)
        self.frm1.place(x=180, y=50)

        self.frm2.config(bg='red', height=500, width=150)
        Label(self.frm2, text='frm2').place(anchor=NW)
        self.frm2.place(x=20, y=50)

        self.frm3.config(bg='yellow', height=40, width=760)
        Label(self.frm3, text='frm3').place(in_=self.frm3, anchor=NW)
        self.frm3.place(x=20, y=5)

        # frm3下的Label
        Label(self.frm3, text='Label Test Test',
              fg='red', font='Verdana 10 bold').place(x=300, y=10)
        # frm2下的Button
        for i in range(9):
            Button(self.frm2, text='Button%d' % i).place(x=20, y=20+i*50, width=100)

        # frm1下的控件
        Label(self.frm1, text='项目资源管理平台',
              fg='red', font='Verdana 10 bold').place(x=100, y=50, height=80, width=400)
        Button(self.frm1, text='1', height=1, width=1).place(x=450, y=450)
        Button(self.frm1, text='2', height=1, width=1).place(x=490, y=450)
        Button(self.frm1, text='3', height=1, width=1).place(x=530, y=450)


if __name__ == '__main__':
    root = Tk()
    A(root)
    mainloop()
Python窗口Tkinter Button详解与位置调整

如何用像素定义button的大小?

需要指定image或者bitmap属性,然后再使用width, height来控制。
默认的button是text类型, width, heigth表示字符个数和行数,指定那些后,意义就变成像素。
例如:

import Tkinter
root = Tkinter.Tk()
b1 = Tkinter.Button(root, bitmap="gray50", width=10, height=10)
b1.pack()
root.mainloop()

那这样的话,我是不是就不能在这个button里输入文字了?
如果要文字,那么需要配合bitmap或者image使用。然后指定compound值。
比如

import Tkinter
root = Tkinter.Tk()
b1 = Tkinter.Button(root, bitmap="info", text="click me", width=150, height=150, compound=Tkinter.LEFT)
b1.pack()
root.mainloop()

Button(按钮)详解

Button 控件是一种标准 Tkinter 控件, 用来展现不同样式的按钮. Button 控件被用以和用户交互, 比如按钮被鼠标点击后, 某种操作被启动. 和 Label 控件类似, 按钮可以展示图片或者文字. 不同的是, Label 控件可以指定字体, Button 控件只能使用单一的字体. Button 上的文字可以多行显示. 
可以将一个 Python 函数或方法绑定到一个 Button 控件. 这个函数或方法将在按钮被点击时执行.

按钮Button控件的属性:

activebackground, activeforeground
类型:颜色;
说明:当按钮被激活时所使用的颜色。

anchor
类型:常量;
说明:控制按钮上内容的位置。使用N, NE, E, SE, S, SW, W, NW,or CENTER这些值之一。默认值是CENTER。

background (bg), foreground (fg)
类型:颜色;
说明:按钮的颜色。默认值与特定平台相关。

bitmap
类型:位图;

borderwidth (bd)
类型:整数;
说明:按钮边框的宽度。默认值与特定平台相关。但通常是1或2象素。

command
类型:回调;
说明:当按钮被按下时所调用的一个函数或方法。所回调的可以是一个函数、方法或别的可调用的Python对象。

cursor
类型:光标;
说明:当鼠标移动到按钮上时所显示的光标。

default
类型:常量;
说明:如果设置了,则按钮为默认按钮。注意这个语法在Tk 8.0b2中已改变。

disabledforeground
类型:颜色;
说明:当按钮无效时的颜色。

font
类型:字体;
说明:按钮所使用的字体。按钮只能包含一种字体的文本。

highlightbackground, highlightcolor
类型:颜色;
说明:控制焦点所在的高亮边框的颜色。当窗口部件获得焦点的时候,边框为highlightcolor所指定的颜色。否则边框为highlightbackground所指定的颜色。默认值由系统所定。

highlightthickness
类型:距离;
说明:控制焦点所在的高亮边框的宽度。默认值通常是1或2象素。

image
类型:图象;
说明:在部件中显示的图象。如果指定,则text和bitmap选项将被忽略。

justify
类型:常量;
说明:定义多行文本如何对齐。可取值有:LEFT, RIGHT, 或 CENTER(默认)。

padx, pady
类型:距离;
说明:指定文本或图象与按钮边框的间距。

relief
类型:常量;
说明:边框的装饰。通常按钮按下时是凹陷的,否则凸起。另外的可能取值有GROOVE, RIDGE, 和 FLAT。

state
类型:常量;
说明:按钮的状态:NORMAL, ACTIVE 或 DISABLED。默认值为NORMAL。

takefocus
类型:标志;
说明:表明用户可以Tab键来将焦点移到这个按钮上。默认值是一个空字符串,意思是如果按钮有按键绑定的话,它可以通过所绑定的按键来获得焦点。

text
类型:字符串;
说明:显示在按钮中的文本。文本可以是多行。如果bitmaps或image选项被使用,则text选项被忽略。

textvariable
类型:变量;
说明:与按钮相关的Tk变量(通常是一个字符串变量)。如果这个变量的值改变,那么按钮上的文本相应更新。

underline
类型:整数;
说明:在文本标签中哪个字符加下划线。默认值为-1,意思是没有字符加下划线。

width, height
类型:距离;
说明:按钮的尺寸。如果按钮显示文本,尺寸使用文本的单位。如果按钮显示图象,尺寸以象素为单位(或屏幕的单位)。如果尺寸没指定,它将根据按钮的内容来计算。

wraplength
类型:距离;
说明:确定一个按钮的文本何时调整为多行。它以屏幕的单位为单位。默认不调整。

点击Button,利用回调函数显示文本内容。

from Tkinter import *
Bu=Tk()
#回调函数
def PrintButton():
    print '荷塘花!'
img=PhotoImage(file='D:/temp/1.gif')
Button(Bu,width=200,height=200,text='press',anchor='c',bg='blue',fg='red',padx=120,pady=120,borderwidth=10,relief='ridge',image=img,compound='bottom',command=PrintButton).pack()
 
Bu.mainloop()

anchor属性:

from Tkinter import *
root = Tk()
 
for a in ['n','s','e','w','ne','nw','se','sw']:
    Button(root,
    text = 'anchor',
    anchor = a,
    width = 30,
    height = 4).pack()
#文本显示的位置。
Button(root,text = 'anchor',width = 30,height =4).pack()
Button(root,text = 'anchor',anchor = 'center',width = 30,height =4).pack()
Button(root,text = 'anchor',anchor = 'n',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 's',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'e',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'w',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'ne',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'nw',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'se',width = 30,height = 4).pack()
Button(root,text = 'anchor',anchor = 'sw',width = 30,height = 4).pack()
 
root.mainloop()

利用按钮退出Label计时器:

def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel."""
after(self, ms, func=None, args) Tkinter的方法。标签实例 在给定时间后调用函数。MS以毫秒为单位指定时间。函数给出了响应调用的函数。额外的参数作为函数调用的参数。返回使用after_cancel取消调度的标识符。 if not func: # I'd rather use time.sleep(ms0.001)
self.tk.call('after', ms)
else:
def callit():
try:
func(*args)
finally:
try:
self.deletecommand(name)
except TclError:
pass
callit.name = func.name
name = self._register(callit)
return self.tk.call('after', ms, name)
回调函数与函数:fun与fun()作为参数时表示的意义不同。

fun作为参数表示是函数

fun()作为参数时表示一个值

config(self, cnf=None, **kw) Tkinter方法。标签实例
配置小部件的资源。资源的值被指定为关键字。
就是使用config来重新给标签属性赋值

程序暂停的几种方法:

#1、导入os模块
import os
     os.system('pause)

#2、导入subprocess模块
import subprocess
      subprocess.call("pause",shell=True)

3、input();
    这种方法不用包含模块,因此这也是最常用的一种暂停手段。

     Python2中的raw_input()和input()语句在Python3中已经被合并到input()中。

程序退出方法:
1、导入os模块

import    os
       os._exit()

os._exit()会直接将python程序终止,之后的所有代码都不会继续执行。

2、导入sys模块

import sys 
     sys.exit()

sys.exit()会引发一个异常:SystemExit,如果这个异常没有被捕获,那么python解释器将会退出。如果有捕获此异常的代码,那么这些代码还是会执行。

计时器示例:

from Tkinter import *
import subprocess
import os
import sys
counter = 0
def counter_label(label):
    counter = 0
    def count():
      global counter
      counter += 1
      #配置属性
      #区间大小
      label.config(width=10, height=2)
      #文本内容
      label.config(text=str(counter/3600%24/10)+str(counter/3600%24%10)+':'+str(counter/60%60/10)+str(counter/60%60%10)+':'+str(counter%60/10)+str(counter%60%10))
      #字体颜色
      label.config(fg='red')
      #label位置
      label.config(anchor='c')
      #after函数的第一个参数设置毫秒数后,调用count函数
      label.after(1, count)
    count()
 
def Pause():
  # subprocess.call("pause",shell=True)
  # os.system('pause')
  # input()
 
  sys.exit()
 
root = Tk()
root.title("计时器")
label = Label(root)
label.pack(side='left')
#查找方法或属性
# print help(label.config)
# print help(label.after)
counter_label(label)
button = Button(root, text='Stop', width=5, command=Pause,anchor='c').pack(side='right')#或command=root.destory小伙窗口
root.mainloop()

学习资源:

https://www.python-course.eu/python_tkinter.php
https://morvanzhou.github.io/tutorials/python-basic/

作者:

喜欢围棋和编程。

 
发布于 分类 编程标签

发表评论

邮箱地址不会被公开。