TKINTER:将功能绑定到打开SimpleDialog的按钮



我正在尝试使用将用户的联系人(名称和电话号码(存储在"电话簿"中的TK Inter编写程序,但也允许用户添加新的联系人。我想将" AddContact"按钮绑定到一个函数,该函数打开一个简单的对话框,要求用户输入他们要添加的新名称和电话号码。然后,我将这些信息显示在"电话簿"中。但是,每次我运行代码时,我都会得到旋转的死亡轮,什么也没有负担。这是我的代码

from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox
import tkinter as tk
from tkinter import simpledialog
def contact(event = None):
    phonenum = listbox.get(listbox.curselection())
    numString.set("Phone Number" + ":" + " " + phonenumbers[phonenum])
def add(event = None):
    application_window = tk.Tk()
    answer = simpledialog.askstring("String", "Enter name, phone number", parent=application_window)
root = Tk()
root.title("Contacts")
phonenumbers = {"John" : "201-453-4324", "Stacy" : "201-453-3564", "Tim" : "832-143-5345", "Maria" : "503-675-3322"}
contacts = phonenumbers.keys()
listbox = Listbox(root)
listbox.grid(row = 0, column = 0)
for c in contacts:
    listbox.insert(END, c)
#Output phone number
numString = StringVar()
numLabel = Label(root, textvariable = numString)
numLabel.grid(row = 4, column = 0, columnspan = 1)
 #Buttons
contactButton = Button(root, text = "Contact Info")
contactButton.grid(row = 2, column = 0)
contactButton.bind("<Button-1>", contact)
addButton = contactButton = Button(root, text = "Add Contact")
addButton.bind("<Button-1>", add)
addButton.grid(row = 3, column = 0)
root.mainloop()

您不需要额外的Tk()调用,也不需要设置父窗口。另外,您应该将命令参数用于按钮而不是绑定:

def add(event = None):
    answer = simpledialog.askstring("String", "Enter name, phone number")
addButton = tk.Button(root, text = "Add Contact", command=add)

最新更新