python 图形用户界面tkinter之按钮Button的使用 您所在的位置:网站首页 iOS1511 python 图形用户界面tkinter之按钮Button的使用

python 图形用户界面tkinter之按钮Button的使用

2023-09-10 15:51| 来源: 网络整理| 查看: 265

创建和设置窗口 from tkinter import * #创建窗口对象 root = Tk() #窗口属性设置 root.title ('窗口标题') root.geometry('300x400') root.configure(bg='blue') root.iconbitmap(r'C:\Users\Administrator\Desktop\iVista 2 OS X Icons ico\ico\Burn.ico')

Mark:使用了窗口的iconbitmap函数更改了图标。

按钮Button属性1 def print1(): print('你好') button = Button(root,text='打印', font=('楷体',20),fg='red',bg='black', anchor='center',command=print1, #command是命令的意思 height=1,width=5,bd=6) button.pack() root.mainloop()

效果图示 在这里插入图片描述 Mark:Button按钮的很多属性和Label标签类似,比如文本(text)、文本字体(font)、字体大小、颜色(fg)、文本在Button按钮中的位置(anchor)、文本中不同行的对齐方式(justify)、按钮的高度和宽度(height、width)、按钮的背景色(bg)等等。和Lable标签相比,Button按钮有回调函数,command=函数名,当点击按钮时,就会执行回调函数的代码块。

按钮Button属性2 def hello(): print('你好') im = PhotoImage(file=r'C:\Users\Administrator\Desktop\图片PNG格式\喜鹊桃花折扇.png') button = Button(root,text='button',command = hello, height=500,width=500,image=im, relief= SUNKEN) button.pack() root.mainloop()

效果图示

在这里插入图片描述 Mark:也可以在Button按钮上显示图片。先将想要显示的图片转化为image对象(PhotoImage(file=‘图片路径’)),然后使用image属性,image=image对象。如果不设置按钮的高度和宽度(height,width),那么显示按钮的大小就是图片的大小。如果设置按钮的高度和宽度,则只会显示图片的一部分。这里,height、width的单位是像素单位。

修改Button属性

       动态的修改按钮Button的属性

def print1(): #button['text']='Now you see me' button.configure(text='Now you see me') button = Button(root,text='打印', font=('楷体',30),fg='red',bg='black', anchor='center',command=print1, height=1,width=20,bd=6) button.pack() root.mainloop()

效果图示 在这里插入图片描述 点击Button按钮后,文本内容变成

在这里插入图片描述 Mark:Button属性可以修改,如果想呈现的效果是已经设置好的Button在点击按钮后属性发生了变化,可以在回调函数里修改Button的属性:Button对象[‘关键参数’]=要修改的值或Button对象.comfigure(关键参数=要修改的值)。

小结:通过Button对象,我们可以在窗口中设置不同外观的按钮。而且,点击Button按钮,可以执行函数中的代码块。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有