首页 > 解决方案 > 有没有办法将文件名更改为用户文本?在 tkinter gui 中?

问题描述

这是我到目前为止所拥有的:

tkinter.py

from tkinter import *
import tkinter.filedialog
import os
import sys


root = Tk()
root.title('Download File')
root.iconbitmap('C:/Users/londo/Downloads/tkinter/Logo.ico')
root.geometry("800x600")
pyexec = sys.executable


def resize():
    root.geometry("800x800")

myLabel = Label(root, text="Rename the file to what ever you want, and download it!")
myLabel.pack(pady=20)

def open():
    PathPy = tkinter.filedialog.askopenfilename(title="Open a file",file=[('downloadtkinter.py')])
    os.system('%s %s' % (pyexec, PathPy))

my_button = Button(root, text="Download", command=open)
my_button.pack(pady=20)


root.mainloop()

错误:

Traceback (most recent call last):
  File "D:\Users\londo\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\londo\Downloads\tkinter\tkintertest2.py", line 21, in open
    PathPy = tkinter.filedialog.askopenfilename(title="Open a file",file=[('downloadtkinter.py')])
  File "D:\Users\londo\AppData\Local\Programs\Python\Python39\lib\tkinter\filedialog.py", line 384, in askopenfilename
    return Open(**options).show()
  File "D:\Users\londo\AppData\Local\Programs\Python\Python39\lib\tkinter\commondialog.py", line 46, in show
    s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad file type "downloadtkinter.py", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"

下载tkinter.py

from tkinter as tk
import os


frame = tk.Tk()
frame.title('Download File Here')
frame.iconbitmap('C:/Users/londo/Downloads/tkinter/Logo.ico')
frame.geometry("800x800")


def resize():
    root.geometry("800x800")

def printInput():
    inp = inputtxt.get(1.0, "end-1c")
    lbl.config(text = "Provided Input: "+inp)

myLabel = Label(root, text="Rename the file to what ever you want, and download it!")
myLabel.pack(pady=20)


inputtxt = tk.Text(frame,
                hight = 1,
                width = 20)
inputtxt.pack()


printButton = tk.Button(frame,
                        text = "Print",
                        command = printInput)
printButton.pack()

lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()

我不知道如何用文本框中的文本更改文件名并上传文件,如果可能的话,请告诉我。谢谢,伦敦(我对 tkinter 很陌生,这个项目可能对我的技能水平来说太先进了)

标签: pythonpython-3.xtkinterfile-uploadfile-rename

解决方案


如果您只想重命名文件,可以使用:

import os
os.rename(firstname,newname)

从这里开始:如何使用 Python 重命名文件


推荐阅读