![](/img/trans.png)
[英]How can I put user input inside text widget and do search in Log file with tkinter using Python
[英]How can I make a simple tkinter input box that creates a file with user input as name using os?
我正在尝试制作 tkinter 输入框来使用操作系统的“触摸”创建文件。 代码附在下面。 它没有创建命名文件,而是给了我以下消息: TypeError: cannot concatenate 'str' and 'instance' objects
我已经在它们之前尝试了带有 # 的 os.system 行,但它什么也没做。 谁能告诉我我需要解决什么才能使它正常工作?
如果这很重要,我的操作系统是 MacOS。
from tkinter import *
import os
os.system("clear")
root = tk.Tk()
def createFile():
#os.system("cd ~")
os.system("touch" + e1)
#os.system.pack()
e1 = Entry(root)
e1.pack()
button1 = Button(root, text="Create File", command=createFile)
button1.pack()
root.mainloop()```
原因是您试图将“触摸”字符串与条目 object 连接。 您应该首先使用.get
方法获取条目文本。 此外, touch
后应该有一个空格,即touch
。 总的来说,为什么需要system
? 例如,在 Windows 中, touch
命令将失败。 Python 中有open
的 function 用于创建和读取文件。 另外我建议不要在导入中使用 *。 linter(例如 pylint)会抱怨这种方法。
我建议的代码是:
import tkinter as tk
import os
os.system("clear")
root = tk.Tk()
def createFile():
# os.system("touch " + e1.get())
# I suggest this:
file = open(e1.get(), 'w')
file.close()
e1 = tk.Entry(root)
e1.pack()
button1 = tk.Button(root, text="Create File", command=createFile)
button1.pack()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.