Python的GUI编程(二)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(ms*0.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()

参考:http://blog.csdn.net/liuxu0703/article/details/60639166

### 回答1: 要将 tkinter 按钮变灰色,可以使用按钮的 `state` 属性并将其设置为 `"disabled"`。例如: ```python import tkinter as tk root = tk.Tk() # 创建一个按钮 btn = tk.Button(root, text="按钮") # 将按钮的状态设置为禁用 btn.config(state="disabled") # 显示按钮 btn.pack() root.mainloop() ``` 这样,按钮就会变为灰色,且无法被点击。如果要恢复按钮的可用状态,可以将 `state` 属性设置为 `"normal"`。例如: ```python # 将按钮的状态设置为可用 btn.config(state="normal") ``` ### 回答2: 要使python tkinter按钮变灰色,可以使用configure()方法来更改按钮的属性。具体步骤如下: 1. 导入tkinter模块: ```python import tkinter as tk ``` 2. 创建主窗口: ```python window = tk.Tk() ``` 3. 创建按钮: ```python button = tk.Button(window, text="按钮") ``` 4. 定义变灰色按钮的函数: ```python def make_button_gray(): button.configure(state="disabled") # 设置按钮为禁用状态 ``` 5. 创建变灰按钮按钮: ```python gray_button = tk.Button(window, text="变灰按钮", command=make_button_gray) ``` 6. 显示按钮和变灰按钮: ```python button.pack() gray_button.pack() ``` 7. 进入主循环,启动程序: ```python window.mainloop() ``` 以上代码创建了一个窗口并包含一个普通按钮和一个变灰按钮。当点击变灰按钮时,普通按钮会变为灰色并且无法点击。你也可以通过更改按钮的其他属性,如foreground和background来改变按钮的外观效果。这些属性可以在configure()方法中进行更改。 ### 回答3: Python的Tkinter库是Python内置的一个GUI(图形用户界面)工具,可以用来创建窗口应用程序。要使Tkinter按钮变灰色,可以使用按钮的属性来设置其状态。 首先,导入Tkinter库和相关模块: ```python from tkinter import * from tkinter import ttk ``` 然后,创建一个窗口: ```python window = Tk() window.title("按钮变灰色示例") ``` 接下来,创建按钮并设置其初始状态: ```python button = ttk.Button(window, text="点击我变灰色") button.state(['!disabled']) button.grid(row=0, column=0, padx=10, pady=10) ``` 然后,定义一个函数来处理按钮点击事件,并在函数中设置按钮的状态为禁用: ```python def disable_button(): button.state(['disabled']) ``` 最后,将函数与按钮的"command"属性关联起来: ```python button.config(command=disable_button) ``` 这样,当按钮被点击时,按钮的状态将被设置为禁用状态,即变为灰色。 最后,运行窗口的主循环,使窗口保持显示: ```python window.mainloop() ``` 以上就是使用Python的Tkinter库实现按钮变灰色的方法。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HySmiley

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值