Python Tkinter按钮没有出现?

时间:2014-06-30 12:45:57

标签: python tkinter calculator

我是tkinter的新手,我在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()

但是当我运行它时,按钮不会出现。有谁知道为什么?谢谢!

4 个答案:

答案 0 :(得分:2)

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

例如,以下是让代码工作的一种方法:

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

gridpack的选择取决于您。如果您在行和列中进行布局,grid是有意义的,因为您可以在调用grid时指定行和列。如果您从左到右或从上到下对齐事物,pack稍微简单一些,就是为了这个目的而设计的。

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

要知道的一件重要事情是,您可以在同一个程序中同时使用packgrid,但不能在具有相同父级的不同窗口小部件上同时使用它们。

答案 1 :(得分:0)

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

尝试使用pack()添加按钮。我不知道为什么你试图在你的代码中指定button_1 = '1'

一个简洁的例子:

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

答案 2 :(得分:0)

您没有打包button_1。代码是:

from tkinter import *

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

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

root.mainloop()

很简单! 希望这有帮助!

答案 3 :(得分:0)

from tkinter import *

calc_window = Tk()

calc_window.title('Calculator Program')

button_1 = Button(text = '1')

button_1.place(x=0,y=0,width = 30, height = 20)

calc_window.mainloop()