Python Tkinter按钮没有出现? [英] Python Tkinter button not appearing?

查看:50
本文介绍了Python Tkinter按钮没有出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是tkinter的新手,我在python中有以下代码:

I'm new to tkinter and I have this code in python:

#import the tkinter module
from tkinter import *
import tkinter


calc_window = tkinter.Tk()
calc_window.title('Calculator Program')


button_1 = tkinter.Button(text = '1', width = '30', height = '20')
button_1 = '1'

calc_window.mainloop()

但是当我运行它时,该按钮没有出现.有人知道为什么吗?谢谢!

But when I run it, the button doesn't appear. Does anyone know why? Thank you!

推荐答案

要显示窗口小部件,需要两个步骤:必须创建窗口小部件,并且必须将其添加到布局中.这意味着您需要使用几何管理器 pack place grid 之一将其放置在其容器中的某个位置.

Getting a widget to appear requires two steps: you must create the widget, and you must add it to a layout. That means you need to use one of the geometry managers pack, place or grid to position it somewhere in its container.

例如,这是使代码正常工作的一种方法:

For example, here is one way to get your code to work:

button_1 = tkinter.Button(text = '1', width = '30', height = '20')
button_1.pack(side="top")

选择 grid pack 由您决定.如果要按行和列进行布局,则 grid 很有意义,因为在调用 grid 时可以指定行和列.如果要从左到右或从上到下对齐,则 pack 会更简单一些,并且为此目的而设计.

The choice of grid or pack is up to you. If you're laying things out in rows and columns, grid makes sense because you can specify rows and columns when you call grid. If you are aligning things left-to-right or top-to-bottom, pack is a little simpler and designed for such a purpose.

注意: place 很少使用,因为它是为精确控制而设计的,这意味着您必须手动计算x和y坐标以及小部件的宽度和高度.这很繁琐,通常会导致窗口小部件对主窗口中的更改无法很好地响应(例如,当用户调整大小时).您还最终得到了一些不灵活的代码.

Note: place is rarely used because it is designed for precise control, which means you must manually calculate x and y coordinates, and widget widths and heights. It is tedious, and usually results in widgets that don't respond well to changes in the main window (such as when a user resizes). You also end up with code that is somewhat inflexible.

要了解的重要一点是,您可以在同一程序中同时使用 pack ,但是不能在具有相同父级的不同小部件上同时使用.

An important thing to know is that you can use both pack and grid together in the same program, but you cannot use both on different widgets that have the same parent.

这篇关于Python Tkinter按钮没有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆