如何从 .get() 传输数据,这将导致从 Tkinter 中删除文本行
Posted
技术标签:
【中文标题】如何从 .get() 传输数据,这将导致从 Tkinter 中删除文本行【英文标题】:How can I transfer data from the .get() which will result into deleting a textline from Tkinter 【发布时间】:2022-01-18 08:42:34 【问题描述】:大家晚上好,请问我的这个关于传输数据以删除文本行的问题的帮助。
Sample.txt consist of:
one
two
three
four
five
这是我的代码:
import tkinter
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Delete line")
def remove_line(fileName, lineToSkip):
with open(fileName, 'r') as read_file:
lines = read_file.readlines()
currentLine = 1
with open(fileName, 'w') as write_file:
for line in lines:
if currentLine == lineToSkip:
pass
else:
write_file.write(line)
currentLine += 1
Numbah = IntVar()
NumbahEntry = Entry(root,textvariable=Numbah,).pack()
sample = remove_line("Sample.txt", Numbah.get())
AcceptButton = Button(root, text="Submit", command=sample,, ,bg="lightgreen").pack()
root.mainloop()
remove_line("Sample.txt", 1) #右边数表示 删除哪一行
我正在尝试通过在输入框上输入一个表示要删除的行的数字来生成结果
【问题讨论】:
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。 【参考方案1】:有几个问题:
if currentLine == lineToSkip:
应该是 if currentLine <= lineToSkip:
sample = remove_line("Sample.txt", Numbah.get())
将立即执行 remove_line(...)
。应该是sample = lambda: remove_line("Sample.txt", Numbah.get())
文件的输出可以简化如下:
def remove_line(fileName, lineToSkip):
with open(fileName, 'r') as read_file:
lines = read_file.readlines()
with open(fileName, 'w') as write_file:
write_file.write(''.join(lines[lineToSkip:]))
完整修改代码:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Delete line")
def remove_line(fileName, lineToSkip):
with open(fileName, 'r') as read_file:
lines = read_file.readlines()
with open(fileName, 'w') as write_file:
write_file.write(''.join(lines[lineToSkip:]))
Numbah = IntVar()
Entry(root,textvariable=Numbah,).pack()
sample = lambda: remove_line("Sample.txt", Numbah.get())
Button(root, text="Submit", command=sample,, ,bg="lightgreen").pack()
root.mainloop()
【讨论】:
以上是关于如何从 .get() 传输数据,这将导致从 Tkinter 中删除文本行的主要内容,如果未能解决你的问题,请参考以下文章
机器学习模型识别可能受益于EGFR TKI的IV期EGFR+NSCLC患者
如何从HttpServletRequest中拿到前端以application/json形式传输的body中的json串