使用按钮单击Tkinter创建新选项卡

时间:2018-05-05 22:40:21

标签: python tkinter

我创建了一个程序,通过单击按钮创建一个新选项卡。 问题是,我想在单击按钮时在该选项卡内创建选项卡和树视图,但我不知道应该为root设置什么。它总是显示此错误:

AttributeError: 'str' object has no attribute 'tk'

这是代码:

from tkinter import *
from tkinter import ttk
import math
import sys

myApp = Tk()
myApp.title(" Program ")                         
myApp.geometry("1000x1200")

tasktabs=ttk.Notebook(myApp)

NewWorkLab=Label(myApp,text="Name: ")
NewWorkLab.grid(row=0,column=2, sticky="W", padx=5,pady=5)

NewWorkEntry=Entry(myApp)
NewWorkEntry.grid(row=0,column=3,sticky="W", padx=5,pady=5)

def AddNewWork():

    TabName=NewWorkEntry.get()

    NewWorkTab=ttk.Frame(tasktabs)
    tasktabs.add(NewWorkTab,text=NewWorkEntry.get())

    NewTree= ttk.Treeview(TabName,height=40)
    NewTree['show'] = 'headings'

    NewTree["columns"]=("1","2","3","4","5","6")

    NewTree.column("1", width=20)
    NewTree.column("2", width=320)
    NewTree.column("3", width=40)
    NewTree.column("4", width=80)
    NewTree.column("5", width=80)
    NewTree.column("6", width=80)

    NewTree.heading("1", text="ID")
    NewTree.heading("2", text="Activities")
    NewTree.heading("3", text="Unit")
    NewTree.heading("4", text="Quantity")
    NewTree.heading("5", text="Unit Cost")
    NewTree.heading("6", text="Total Cost")

    NewTree.grid(row=2,column=0,pady=10,padx=0)

AddWorkButton=Button(myApp,text=' Add ', command=AddNewWork)
AddWorkButton.grid(row=0,column=4, sticky="W", padx=5, pady=5)


tasktabs.grid(row=1,column=0,columnspan=4,padx=5)   

myApp.mainloop()

1 个答案:

答案 0 :(得分:1)

永远记住一件事,在Tkinter中你不能存储任何带有变量名的小部件;它有自己的数字存储方式,所以如果你认为你将小部件存储为输入框中的值的名称,那么它也是正确的。它只是暂时保存变量的引用,稍后无法使用变量名检索该值。

from tkinter import *
from tkinter import ttk
import math
import sys

myApp = Tk()
myApp.title(" Program ")
myApp.geometry("1000x1200")

tasktabs=ttk.Notebook(myApp)

NewWorkLab=Label(myApp,text="Name: ")
NewWorkLab.grid(row=0,column=2, sticky="W", padx=5,pady=5)

NewWorkEntry=Entry(myApp)
NewWorkEntry.grid(row=0,column=3,sticky="W", padx=5,pady=5)

def AddNewWork():


    TabName=ttk.Frame(tasktabs)
    tasktabs.add(TabName,text=NewWorkEntry.get())

    NewTree= ttk.Treeview(TabName,height=40)
    NewTree['show'] = 'headings'

    NewTree["columns"]=("1","2","3","4","5","6")

    NewTree.column("1", width=20)
    NewTree.column("2", width=320)
    NewTree.column("3", width=40)
    NewTree.column("4", width=80)
    NewTree.column("5", width=80)
    NewTree.column("6", width=80)

    NewTree.heading("1", text="ID")
    NewTree.heading("2", text="Activities")
    NewTree.heading("3", text="Unit")
    NewTree.heading("4", text="Quantity")
    NewTree.heading("5", text="Unit Cost")
    NewTree.heading("6", text="Total Cost")

    NewTree.grid(row=2,column=0,pady=10,padx=0)

AddWorkButton=Button(myApp,text=' Add ', command=AddNewWork)
AddWorkButton.grid(row=0,column=4, sticky="W", padx=5, pady=5)


tasktabs.grid(row=1,column=0,columnspan=4,padx=5)

myApp.mainloop()