当用户与另一个小部件(在本例中为菜单项)交互时,我希望生成一行新的GUI项。
理想情况下,我将能够让用户按需生成新的仪表输入行。每个新行都应插入到网格下方的下一个位置。
我为希望输入的小部件行生成了一个类。我可以将其分配给一个新变量,它可以按预期工作。当我尝试将其添加到菜单项的命令选项时,无论是否按下按钮,它都会立即创建它。
from tkinter import *
from tkinter.ttk import *
class instroRow:
def __init__(self, instroNumber, master):
lbl_instroNo = Label(master, text=instroNumber)
lbl_instroNo.grid(column=0, row=instroNumber+1, padx=5)
combo_instroType = Combobox(master, values=["Thermocouple","Accel"])
combo_instroType.grid(column=2, row=instroNumber+1, padx=5)
entry_instroQuantity = Entry(master)
entry_instroQuantity.grid(column=4, row=instroNumber+1, padx=5)
combo_instroRecordingSS = Checkbutton(master, text="SS")
combo_instroRecordingSS.grid(column=6, row=instroNumber+1, padx=5)
combo_instroRecordingT = Checkbutton(master, text="T")
combo_instroRecordingT.grid(column=7, row=instroNumber+1, padx=5)
combo_instroRecordingD = Checkbutton(master, text="D")
combo_instroRecordingD.grid(column=8, row=instroNumber+1, padx=5)
window = Tk()
window.title("Instro")
window.geometry("1000x500")
#add menu bar
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label='New', command=instroRow(3,window)) # I want this menu item to create a new instro row.
new_item.add_command(label='Exit', command=window.destroy)
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
#grid
sh = Separator(window, orient=HORIZONTAL)
sh.grid(column=0, row=1, columnspan=10, sticky="EW")
s1 = Separator(window, orient=VERTICAL)
s1.grid(column=1, row=0, rowspan=5, sticky="NS")
s2 = Separator(window, orient=VERTICAL)
s2.grid(column=3, row=0, rowspan=5, sticky="NS")
s3 = Separator(window, orient=VERTICAL)
s3.grid(column=5, row=0, rowspan=5, sticky="NS")
s4 = Separator(window, orient=VERTICAL)
s4.grid(column=9, row=0, rowspan=5, sticky="NS")
#instro header
lbl_Header_instroNo = Label(window, text="Instro No.")
lbl_Header_instroNo.grid(column=0, row=0, padx=5)
lbl_Header_instroType = Label(window, text="Type")
lbl_Header_instroType.grid(column=2, row=0, padx=5)
lbl_Header_instroQuantity = Label(window, text="No. Off")
lbl_Header_instroQuantity.grid(column=4, row=0, padx=5)
lbl_Header_instroRecording = Label(window, text="Recording Type")
lbl_Header_instroRecording.grid(column=6, row=0, padx=5, columnspan=3)
row1 = instroRow(1,window)
row2 = instroRow(2,window)
window.mainloop()
该代码当前在运行时而不是在按下菜单项时会创建一个全新的行。