如何在python 3.x tkinter中保存文本框(String和Int)中的文本

时间:2015-01-09 06:07:12

标签: python tkinter save

我正在尝试从6个texbox中保存一些名称和值,2个是字符串,4个是整数,在.txt或.doc中但它不起作用

我在Windows 8.1中使用python 3.4,有人可以帮助我,我无法在python 3.4中找到任何信息或示例来保存我在这6个texbox中写的任何东西 我有一个按钮来调用函数mSave

我有以下代码要保存但不能正常工作

def mSave():
    filename = asksaveasfilename(defaultextension='.txt',
                                 filetypes=(('Text files', '*.txt'),
                                            ('Python files', '*.py *.pyw'),
                                            ('All files', '*.*')))
  if filename:
     with open(filename, 'w') as stream:
          stream.write(self.gettext())

Python说

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\idlelib\run.py", line 121, in main
    seq, request = rpc.request_queue.get(block=True, timeout=0.05)
  File "C:\Python34\lib\queue.py", line 175, in get
    raise Empty
queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\\ManualTab.py", line 608, in mSave
    filename = asksaveasfilename(defaultextension='.txt',
NameError: name 'asksaveasfilename' is not defined

请求帮助

1 个答案:

答案 0 :(得分:0)

我找到了答案

ok首先,对于python 3.4,我必须使用

from tkinter import *

但这并不意味着它会导入ALL所以我必须调用

from tkinter import filedialog
from tkinter.filedialog import asksaveasfilename

如果有人需要它,它与open相同

from tkinter.filedialog import askopenfilename

现在我终于可以致电我的职能了

def mSave():
  filename = asksaveasfilename(defaultextension='.txt',filetypes = (('Text files', '*.txt'),('Python files', '*.py *.pyw'),('All files', '*.*')))
  if filename is None:
    return
  file = open (filename, mode = 'w')
  name1 = TubeLenghtVal_1.get()          
  name2 = TubeLenghtVal_2.get()

  # or whatever you assign the name of the variable, for me is TubeLenghtVal_2 = StringVar() and for integer I have Vol_Val = IntVar()
  all = name1 + " , " + name + " , " + (str(Vol_Val))
  file.write(all)
  file.close()

这就是