如何通过在Tkinter中按下按钮来创建新按钮

时间:2019-01-21 16:38:37

标签: python tkinter

我有一个程序,当单击一个按钮时,我需要生成另一个按钮。不必专门包装。

我尝试将command=部分设置为等于有newbutton = tk.Button(root, text=fields[0])的方法,但这无效。

from tkinter import *
import tkinter as tk

class MainWindow(tk.Frame):
    counter = 0
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Create new hotlink",
                            command=self.create_window)
        self.button.pack(side="top")

    def create_window(self):
        self.counter += 1
        t = tk.Toplevel(self)
        t.wm_title("Create New Hotlink")
        fields = 'Hotlink Name', 'URL'

        def fetch(entries):
            for entry in entries:
                field = entry[0]
                text = entry[1].get()
                print('%s: "%s"' % (field, text))

        def makeform(root, fields):
            entries = []
            for field in fields:
                row = Frame(root)
                lab = Label(row, width=15, text=field, anchor='w')
                ent = Entry(row)
                row.pack(side=TOP, fill=X, padx=5, pady=5)
                lab.pack(side=LEFT)
                ent.pack(side=RIGHT, expand=YES, fill=X)
                entries.append((field, ent))
            return entries

        def button2():
            newButton = tk.Button(root, text=fields[0])

        ents = makeform(t, fields)
        t.bind('<Return>', (lambda event, e=ents: fetch(e)))
        b2 = Button(t, text='Save', command=button2())
        b2.pack(side=LEFT, padx=5, pady=5)

if __name__ == "__main__":
    root = tk.Tk()
    main = MainWindow(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

2 个答案:

答案 0 :(得分:1)

之所以不起作用,是因为您正在调用的命令是command=button2(),而应为command=button2。调用命令时不应包含()

此外,由于未定义newButton的展示位置,因此它没有放置在任何地方。使用.pack定义时,它会出现。

在此处查看从您的代码中摘录的内容:

    def button2():
    newButton = tk.Button(root, text=fields[0])
    newButton.pack(side=RIGHT)

ents = makeform(t, fields)
t.bind('<Return>', (lambda event, e=ents: fetch(e)))
b2 = Button(t, text='Save', command=button2)
b2.pack(side=LEFT, padx=5, pady=5)

您的其余代码很好,因此为什么我只包含了此代码段。

答案 1 :(得分:1)

这是因为您分配的不是函数本身,而是值command=button()中返回的函数,您应该这样做:

b2 = Button(t, text='Save', command=button2)

button2()函数中,您也忘记打包新按钮了:

def button2():
    newButton = tk.Button(root, text=fields[0])
    newButton.pack()

按下“保存”按钮后,将创建新的按钮

enter image description here