tkinter:将函数绑定到打开simpledialog的按钮

时间:2017-04-21 22:04:52

标签: python python-3.x tkinter

我正在尝试使用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()

1 个答案:

答案 0 :(得分:1)

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

def add(event = None):
    answer = simpledialog.askstring("String", "Enter name, phone number")

addButton = tk.Button(root, text = "Add Contact", command=add)