Python 程序中的“StringVar"问题 [英] Issue with 'StringVar' in Python Program
问题描述
我正在尝试使用 Tkinter 在 Python 中编写一个非常简单的 UI.我在 StringVar
类中遇到了一个小问题.问题是,当我运行 python 脚本时,我在初始化 StringVar
变量的行上收到一个错误.我已经写了一个关于这个问题的示例程序,我想开始工作:
I am trying to write a VERY simple UI in Python using Tkinter. I have run into a small problem with the StringVar
class. The thing is, when I run the python script, I get an error on the line that initializes the StringVar
variable. I have written a sample program with this issue that I would like to get working:
from Tkinter import *
var = StringVar()
var.set('test');
当我通过 python 运行它时,我看到这个错误:
When I run it through python I see this error:
$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
var = StringVar()
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 254, in __init__
Variable.__init__(self, master, value, name)
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 185, in __init__
self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Exception AttributeError: "StringVar instance has no attribute '_tk'" in <bound method StringVar.__del__ of <Tkinter.StringVar instance at 0xb73cc80c>> ignored
我感觉这是我的 Python 安装问题,但可能是我做错了什么?如果这有所不同,我将在 Ubuntu Linux 上使用 python 版本 2.6.5.
I have a feeling that this is an issue with my Python installation, but it may be that I am doing something wrong? I am using python version 2.6.5 on Ubuntu Linux if that makes a difference.
推荐答案
我认为您可能需要在调用 StringVar 之前显式调用 Tk().
I think you might need to call Tk() explicitly before invoking StringVar.
就这样做:
from Tkinter import *
Tk() # Add this
var = StringVar()
var.set('test');
这篇关于Python 程序中的“StringVar"问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!