Python Tkinter button not appearing?

℡╲_俬逩灬. 提交于 2021-01-27 17:11:48

问题


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!


回答1:


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")

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.

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.

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.




回答2:


from tkinter import *
import tkinter


calc_window = tkinter.Tk()
calc_window.title('Calculator Program')
frame = Frame(calc_window )
frame.pack()


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


calc_window.mainloop()

try adding the button using pack(). i donno why u tried to assign button_1 = '1' in your code

a neat example:

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(
            frame, text="QUIT", fg="red", command=frame.quit
            )
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="Hello", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()



回答3:


You're not packing the button_1. The code is:

from tkinter import *

root = Tk()
root.title('Calculator Program')

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

root.mainloop()

It's simple! Hope this helps!



来源:https://stackoverflow.com/questions/24490475/python-tkinter-button-not-appearing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!