对于这些简单的问题,很抱歉,我是一个初学者。我想获取信息(员工的姓名,工资和年龄),并在窗口的标题(姓名,工资,年龄)中显示该列表。但是我不知道如何获取信息并在列表中进行管理。
from tkinter import *
from tkinter.ttk import *
addemploye = Tk()
addemploye.geometry("400x400")
Label(addemploye, text="Name").pack()
e1 = Entry(addemploye, width=20).pack()
Label(addemploye, text="Salary").pack()
e2 = Entry(addemploye, width=20).pack()
Label(addemploye, text="Age").pack()
e3 = Entry(addemploye, width=20).pack()
B2 = Button(addemploye , text = "Save", command = getting)
B2.pack()
B3 = Button(addemploye, text="Close", command=addemploye.destroy)
B3.pack()
window = Tk()
window.title("Table with add, edit and delete")
window.geometry('400x400')
window.title("Table with add employee")
window.geometry('500x500')
btn = Button(window, text="+ add new employee",command = addemployee)
btn.place(relx=0.95, rely=0.9, anchor=SE)
window.mainloop()
答案 0 :(得分:1)
以下几点:创建多个Tk()
实例。参见Why are multiple instances of Tk discouraged?。而是将新窗口创建为Toplevel()
。
Button()
命令参数需要一个函数,因此我编写了一个函数,该函数使用Toplevel()
创建对话框窗口。
在小部件上调用pack()
时,返回值将来自pack()
而不是小部件创建。下面的示例中,变量e2
将获得值None
。
e2 = Entry(addemploye, width=20).pack()
首先创建小部件,然后打包:
e2 = Entry(addemploye, width=20)
e2.pack()
变量e2
现在将指向条目。您还可以通过将每个Entry()
与StringVar()
关联来管理条目中的文本。
我举了一个例子,其中我将条目中的数据附加到列表中。然后,您可以将该列表保存到所需的任何位置。
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('500x500+900+50')
window.title("Table with add employee")
table_row = [] # List to hold data from addemployee
def addemployee():
dialog = Toplevel(window)
dialog.geometry('400x400+800+250')
dialog.title('Add new employee')
dialog.focus_set()
Label(dialog, text="Name").pack()
e1 = Entry(dialog, width=20)
e1.pack()
Label(dialog, text="Salary").pack()
e2 = Entry(dialog, width=20)
e2.pack()
Label(dialog, text="Age").pack()
e3 = Entry(dialog, width=20)
e3.pack()
def getting():
table_row.append(e1.get()) # Append Name to table_row
table_row.append(e2.get()) # etc.
table_row.append(e3.get())
# Save table_row to where you want it
print(table_row) # For debugging
B2 = Button(dialog , text = "Save", command=getting)
B2.pack()
B3 = Button(dialog, text="Close", command=dialog.destroy)
B3.pack()
btn = Button(window, text="+ add new employee", command=addemployee)
btn.place(relx=0.95, rely=0.9, anchor=SE)
window.mainloop()