📜  Python|在 tkinter 中创建一个按钮

📅  最后修改于: 2022-05-13 01:55:42.827000             🧑  作者: Mango

Python|在 tkinter 中创建一个按钮

Tkinter 是 Python 的标准 GUI(图形用户界面)包。它是Python自带的最常用的 GUI 应用程序包之一。让我们看看如何使用 Tkinter 创建一个按钮。

请按照以下步骤操作:

  1. 在Python 2.x 中导入 tkinter 模块 # Tkinter。 (注大写T)
  2. 创建主窗口(root = Tk())
  3. 添加任意数量的小部件。

导入 tkinter 模块与导入任何其他模块相同。

import tkinter   # In Python 3.x

import Tkinter   # In python 2.x. (Note Capital T)

tkinter.ttk模块提供对 Tk 8.5 中引入的 Tk 主题小部件集的访问。如果尚未针对 Tk 8.5 编译Python ,则在安装了Tile的情况下仍然可以访问此模块。使用 Tk 8.5 的前一种方法提供了额外的好处,包括 X11 下的抗锯齿字体渲染和窗口透明度。
tkinter.ttk的基本思想是尽可能将实现小部件行为的代码与实现其外观的代码分开。 tkinter.ttk用于创建tkinter本身无法实现的现代 GUI(图形用户界面)应用程序。

代码 #1:使用 Tkinter 创建按钮。

Python3
# import everything from tkinter module
from tkinter import *   
 
# create a tkinter window
root = Tk()             
 
# Open window having dimension 100x100
root.geometry('100x100')
 
# Create a Button
btn = Button(root, text = 'Click me !', bd = '5',
                          command = root.destroy)
 
# Set the position of button on the top of window.  
btn.pack(side = 'top')   
 
root.mainloop()


Python3
# import tkinter module
from tkinter import *       
 
# Following will import tkinter.ttk module and
# automatically override all the widgets
# which are present in tkinter module.
from tkinter.ttk import *
 
# Create Object
root = Tk()
 
# Initialize tkinter window with dimensions 100x100            
root.geometry('100x100')    
 
btn = Button(root, text = 'Click me !',
                command = root.destroy)
 
# Set the position of button on the top of window
btn.pack(side = 'top')    
 
root.mainloop()


输出:


在不使用tk主题小部件的情况下创建 Button

使用tk主题小部件 (tkinter.ttk) 创建 Button。这将为您提供现代图形的效果。效果会从一个操作系统更改为另一个,因为它基本上是为了外观。

代码#2:

Python3

# import tkinter module
from tkinter import *       
 
# Following will import tkinter.ttk module and
# automatically override all the widgets
# which are present in tkinter module.
from tkinter.ttk import *
 
# Create Object
root = Tk()
 
# Initialize tkinter window with dimensions 100x100            
root.geometry('100x100')    
 
btn = Button(root, text = 'Click me !',
                command = root.destroy)
 
# Set the position of button on the top of window
btn.pack(side = 'top')    
 
root.mainloop()

输出:

注意:参见两个代码的输出,第二个输出中不存在 BORDER,因为tkinter.ttk不支持边框。此外,当您将鼠标悬停在两个按钮上时,ttk.Button 将改变其颜色并变为浅蓝色(效果可能会从一个操作系统更改为另一个),因为它支持现代图形,而对于简单的按钮,它不会改变颜色,因为它不支持现代图形。