Python 尝试将IntVar()赋值给变量时获取AttributeError

Python 尝试将IntVar()赋值给变量时获取AttributeError,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我的代码: #!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Sun Jan 22 14:47:36 2017 @author: Jose Chong """ import json try: import tkinter as tk except ImportError: import Tkinter as tk import os import pymsgbox filepath = os.path

我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 14:47:36 2017

@author: Jose Chong
"""
import json
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

import os
import pymsgbox

filepath = os.path.expanduser(r'~\Documents\joseDzirehChongToDoList\toDoListSaveFile.json')

checkboxList = []

def checkSaveFile():

    def checkExistenceOfSaveFile():
        if not os.path.isdir(os.path.expanduser(r'~\Documents\joseDzirehChongToDoList')):
            os.makedirs(os.path.expanduser(r'~\Documents\joseDzirehChongToDoList'), 777)

        if not os.path.isfile(filepath):
            open(filepath, 'w')
            open(filepath).close()

    def checkIfSaveFileIsEmpty():
        global checkboxList
        if os.path.getsize(filepath) == 0:
            with open (filepath, 'w') as outfile:
                    json.dump(checkboxList, outfile)


        with open(filepath) as infile:    
             checkboxList = json.load(infile)
    checkExistenceOfSaveFile()
    checkIfSaveFileIsEmpty()
    try:
        open(filepath, 'w')
        open(filepath).close()
    except (IOError, ValueError):

        pymsgbox.alert("""You're not supposed to see this message ever. If you do, that means your save file is either missing or corrupted, and my methods of stopping that have failed. Please email me at 'josedzirehchong@gmail.com' with a copy of your save file so I can tell what went wrong.

Click the button below to exit, the red button in the corner doesn't work.""", 'Broken Save File')

checkSaveFile()

var = tk.IntVar()

def loadToJSON():
    with open(filepath, 'w') as outfile:
        json.dump(checkboxList, outfile)

class CheckboxRow(tk.Frame):
    def __init__(self, master, text):
        self.text = text
        tk.Frame.__init__(self, master)
        checkbox = tk.Checkbutton(self, text=text, variable=var)
        checkbox.pack(side=tk.LEFT)

        deleteItem = tk.Button(self, text="x", bg="red", fg="white",
                                activebackground="white", activeforeground="red",
                                command=self.destroyCheckbox)
        deleteItem.pack(side=tk.RIGHT)
        newItem = [self.text, var.get()]
        self.master.master.checkboxList.append(newItem)
        loadToJSON()

    def destroyCheckbox(self, text):
        self.text = text
        newItem = [self.text, var.get()]
        self.master.master.checkboxList.remove(newItem)
        self.destroy()
        loadToJSON()


class CheckboxArea(tk.Frame):
    def add(self, name):
        row = CheckboxRow(self, name)
        row.pack(fill=tk.X)

class InputStuff(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        prompt = tk.Label(self, text="What do you want your checkbox to be for?")
        prompt.pack()

        bottomInput = tk.Frame(self)
        self.entry = tk.Entry(bottomInput, bd=3)
        self.entry.pack(side=tk.LEFT)
        buttonConfirm = tk.Button(bottomInput, text="Confirm", command=self.drawCheckbox)
        buttonConfirm.pack(side=tk.LEFT)
        bottomInput.pack()

        buttonDone = tk.Button(self, text = "Close Input", command=master.hideInputStuff)
        buttonDone.pack()

    def drawCheckbox(self, event=None):
        self.master.add(self.entry.get())
        self.entry.delete(0, tk.END)

class MainWindow(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        self.checkboxList = []

        self.checkboxArea = CheckboxArea(self)
        self.checkboxArea.pack(fill=tk.X)

        self.inputStuff = InputStuff(self)
        self.addButton = tk.Button(self, text="Add Item", command=self.showInputStuff)

        self.hideInputStuff() # start with "add" button active

        self.load()

    def load(self):
        for savedCheckbox in checkboxList:
            checkboxRow = tk.Frame(checkboxArea)
            checkboxRow.pack(fill=tk.X)
            checkbox1 = tk.Checkbutton(checkboxRow, text=savedCheckbox[0], variable=var)
            checkbox1.pack(side=tk.LEFT)
            deleteItem = tk.Button(checkboxRow, text="x", bg="red", fg="white",
                                activebackground="white", activeforeground="red",
                                command=lambda c=savedCheckbox, r=checkboxRow: destroyCheckbox(c, r))
            deleteItem.pack(side=tk.RIGHT)

            loadToJSON()

    def add(self, name):
        self.checkbox_area.add(name)
        self.checkboxList.append(name)

    def showInputStuff(self):
        self.addButton.pack_forget()
        self.input_stuff.pack()
        self.input_stuff.entry.focus()
        self.master.bind('<Return>', self.input_stuff.drawCheckbox)

    def hideInputStuff(self):
        self.inputStuff.pack_forget()
        self.addButton.pack()
        self.master.unbind('<Return>')

def main():
    master = tk.Tk()
    master.title("To-Do List (with saving!)")
    master.geometry("300x300")
    win = MainWindow(master)
    win.pack(fill=tk.X)
    master.mainloop()

if __name__ == "__main__":
    main()
#/usr/bin/env python
#-*-编码:utf-8-*-
"""
创建于2017年1月22日星期日14:47:36
@作者:何塞·庄
"""
导入json
尝试:
将tkinter作为tk导入
除恐怖外:
将Tkinter作为tk导入
导入操作系统
导入pymsgbox
filepath=os.path.expanduser(r'~\Documents\josedzirehcongtodolist\toDoListSaveFile.json')
复选框列表=[]
def checkSaveFile():
def CHECKEXISTEOFSAVEFILE():
如果不是os.path.isdir(os.path.expanduser(r'~\Documents\josedzirehcongtodolist'):
makedirs(os.path.expanduser(r'~\Documents\josedzirehcongtodolist'),777)
如果不是os.path.isfile(文件路径):
打开(文件路径“w”)
打开(文件路径)。关闭()
def checkIfSaveFileIsEmpty():
全局复选框列表
如果os.path.getsize(filepath)==0:
将open(filepath,'w')作为输出文件:
dump(复选框列表,输出文件)
以打开(文件路径)作为填充:
checkboxList=json.load(infle)
checkExistenceOfSaveFile()
checkIfSaveFileIsEmpty()
尝试:
打开(文件路径“w”)
打开(文件路径)。关闭()
除了(IOError、VALUERROR):
pymsgbox.alert(““”您不应该看到此消息。如果您看到此消息,则表示您的保存文件丢失或已损坏,并且我的停止方法已失败。请发送电子邮件至'josedzirehchong@gmail.com“有一份保存文件的副本,这样我就可以知道出了什么问题。
单击下面的按钮退出,角落中的红色按钮不起作用。“”,“损坏的保存文件”)
checkSaveFile()
var=tk.IntVar()
def loadToJSON():
将open(filepath,'w')作为输出文件:
dump(复选框列表,输出文件)
类别CheckboxRow(传统框架):
定义初始化(自、主、文本):
self.text=文本
tk.Frame.\uuuuu init\uuuuuuu(自,主)
checkbox=tk.Checkbutton(self,text=text,variable=var)
复选框包装(侧面=左侧)
deleteItem=tk.按钮(self,text=“x”,bg=“red”,fg=“white”,
activebackground=“白色”,activeforeground=“红色”,
command=self.destroy(复选框)
deleteItem.pack(侧面=右侧)
newItem=[self.text,var.get()]
self.master.master.checkboxList.append(newItem)
loadToJSON()
def销毁复选框(自身,文本):
self.text=文本
newItem=[self.text,var.get()]
self.master.master.checkboxList.remove(newItem)
自我毁灭
loadToJSON()
类复选框区域(tk.框架):
def添加(自我,姓名):
行=复选框行(self,name)
行包装(填充=tk.X)
类InputStuff(tk.Frame):
定义初始化(自,主=无,**kwargs):
tk.Frame.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(自我,主控,**kwargs)
prompt=tk.Label(self,text=“您希望您的复选框用于什么?”)
prompt.pack()
bottomInput=tk.Frame(自)
self.entry=tk.entry(底部输入,bd=3)
自进式包装(侧面=左侧)
buttonConfirm=tk.Button(底部输入,text=“确认”,命令=self.drawCheckbox)
按钮固定。包装(侧面=左侧)
bottomInput.pack()
buttonone=tk.Button(self,text=“关闭输入”,command=master.hideInputStuff)
buttonDone.pack()
def drawCheckbox(自身,事件=无):
self.master.add(self.entry.get())
self.entry.delete(0,tk.END)
类主窗口(tk.Frame):
定义初始化(自,主=无,**kwargs):
tk.Frame.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(自我,主控,**kwargs)
self.checkboxList=[]
self.checkboxArea=checkboxArea(self)
self.checkboxArea.pack(fill=tk.X)
self.inputStuff=inputStuff(self)
self.addButton=tk.Button(self,text=“Add Item”,command=self.showInputStuff)
self.hideInputStuff()#以激活“添加”按钮开始
self.load()
def加载(自):
对于复选框列表中的savedCheckbox:
checkboxRow=tk.框架(checkboxArea)
checkboxRow.pack(填充=tk.X)
checkbox1=tk.Checkbutton(checkboxRow,text=savedCheckbox[0],variable=var)
复选框1.包装(侧面=左侧)
deleteItem=tk.按钮(复选框行,text=“x”,bg=“red”,fg=“white”,
activebackground=“白色”,activeforeground=“红色”,
command=lambda c=savedCheckbox,r=checkboxRow:destroyCheckbox(c,r))
deleteItem.pack(侧面=右侧)
loadToJSON()
def添加(自我,姓名):
self.checkbox\u区域添加(名称)
self.checkboxList.append(名称)
def showInputStuff(自身):
self.addButton.pack_-forget()
self.input_stuff.pack()
self.input\u stuff.entry.focus()
self.master.bind(“”,self.input\u stuff.drawCheckbox)
def hideInputStuff(自身):
self.inputStuff.pack\u-forget()
self.addButton.pack()
自我控制解除绑定(“”)
def main():
master=tk.tk()
master.title(“待办事项列表(带保存!)”)
几何硕士(“300x300”)
win=主窗口(主窗口)
win.pack(填充=tk.X)
master.mainloop()
如果名称=“\uuuuu main\uuuuuuuu”:
main()
我知道它坏得很厉害。我不想在其他事情上得到任何帮助,只是属性错误

完全错误:

runfile('C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile/toDoListToCompile.py', wdir='C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile')
Traceback (most recent call last):

  File "<ipython-input-78-a1f8f63a42cc>", line 1, in <module>
    runfile('C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile/toDoListToCompile.py', wdir='C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile')

  File "C:\Users\Josalina\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Users\Josalina\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile/toDoListToCompile.py", line 51, in <module>
    var = tk.IntVar()

  File "C:\Users\Josalina\Anaconda3\lib\tkinter\__init__.py", line 351, in __init__
    Variable.__init__(self, master, value, name)

  File "C:\Users\Josalina\Anaconda3\lib\tkinter\__init__.py", line 233, in __init__
    self._root = master._root()

AttributeError: 'NoneType' object has no attribute '_root'
runfile('C:/Users/Josalina/Desktop/Coding/Language-Python/to-do-list-to-compile/toDoListToCompile.py',wdir='C:/Users/Josalina/Desktop/Coding/Language-Python/to-do-list-to-compile')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
runfile('C:/Users/Josalina/Desktop/Coding/Language-Python/to-do-list-to-compile/topolistto-compile.py',wdir='C:/Users/Josalina/Desktop/Coding/Language-Python/to-do-list-to-compile')
文件“C:\Users\Josalina\Anaconda3\lib\site packages\spyder\utils\site\sitecustomize.py”,第866行,在runfile中
execfile(文件名、命名空间)
文件“C:\Users\Josalina\Anaconda3\lib\site packages\spyder\utils\site\sitecustomize.py”,第102行,在execfile中
执行官(
import tkinter as tk
var = tk.IntVar()
Traceback (most recent call last):
  File "./qtest.py", line 4, in <module>
    var = tk.IntVar()
  File "/opt/python3.6/lib/python3.6/tkinter/__init__.py", line 499, in __init__
    Variable.__init__(self, master, value, name)
  File "/opt/python3.6/lib/python3.6/tkinter/__init__.py", line 314, in __init__
    self._root = master._root()
AttributeError: 'NoneType' object has no attribute '_root'