tkinter 和 python3.x 按钮配置
tkinter and python3.x button config
我正在尝试将字符串写入文本。这是代码:
def retrieve_input():
inputValue = textBox.get("1.0", "end-1c")
c = inputValue
def open():
f = open("writetest.txt", "a")
def write_input():
f.write(c)
filemenu.add_command(label="Write to txt", command=lambda:retrieve_input())
试了很多方法都没有成功,整个代码又长又不好看,我试着学习写和加载的命令。
我不确定你的缩进是否真的和你的 post 一样,但这里有一个更简洁的方法:
def retrieve_input():
inputValue = textBox.get("1.0", "end-1c")
c = inputValue
with open("writetest.txt", "a") as f:
f.write(c)
我摆脱了所有没有理由的功能。此外,我选择使用 with
指令来处理文件。
此外,您的函数可以更短:
def write_input():
with open("writetest.txt", 'a') as f:
f.write(textBox.get("1.0", "end-1c"))
请注意,您打开了文件,但之后没有关闭它。这可能会导致内存泄漏。使用 with
块可以保护您免受此类事情的影响,因为它会自动关闭文件。此外,在您的代码中, textBox
未定义,因此您需要将其作为参数传递,或将其声明为 global
(避免后者)。
我正在尝试将字符串写入文本。这是代码:
def retrieve_input():
inputValue = textBox.get("1.0", "end-1c")
c = inputValue
def open():
f = open("writetest.txt", "a")
def write_input():
f.write(c)
filemenu.add_command(label="Write to txt", command=lambda:retrieve_input())
试了很多方法都没有成功,整个代码又长又不好看,我试着学习写和加载的命令。
我不确定你的缩进是否真的和你的 post 一样,但这里有一个更简洁的方法:
def retrieve_input():
inputValue = textBox.get("1.0", "end-1c")
c = inputValue
with open("writetest.txt", "a") as f:
f.write(c)
我摆脱了所有没有理由的功能。此外,我选择使用 with
指令来处理文件。
此外,您的函数可以更短:
def write_input():
with open("writetest.txt", 'a') as f:
f.write(textBox.get("1.0", "end-1c"))
请注意,您打开了文件,但之后没有关闭它。这可能会导致内存泄漏。使用 with
块可以保护您免受此类事情的影响,因为它会自动关闭文件。此外,在您的代码中, textBox
未定义,因此您需要将其作为参数传递,或将其声明为 global
(避免后者)。