简体   繁体   English

将文本输出到文件 Tkinter

[英]Outputting text to file Tkinter

when I ask it to output entry box to file it doesn't do anything and since I'm new to python I'm a bit stuck, I know this is a simple problem but I'm not too sure how to fix it.当我要求它向 output 输入框归档时,它什么也没做,因为我是 python 的新手,所以我有点卡住了,我知道这是一个简单的问题,但我不太确定如何解决它。 Please help.请帮忙。

import tkinter as tk
from PIL import ImageTk
window= tk.Tk()

def SignUp ():
    text = username_entry.get()
    file= open(r"C:/Users/willi/OneDrive/Documents/Scripts/username_info.txt", "w") 
    file.write(text)
    file.close()

    username_entry.delete(0, tk.END)
    password_entry.delete(0, tk.END)

def createNewWindow():
    window1 = tk.Toplevel(window)
    canvas= tk.Canvas(window1,width=1920,height=1080)
    canvas.create_image(0,0,anchor=tk.NW, image= Main)
    canvas.pack()
    signup_button=tk.Button(window1,width=23, text="Register!", font="CCDutchCourage2", fg="white", height=1, relief="flat", bg="#183936", command=SignUp)
    signup_button.place(x=840, y=665)
    username_entry= tk.Entry(window1,width=14, bg="#183936", font=('Ariston Comic Demo Regular', 35), relief="flat")
    username_entry.place(x=776, y=447)
    password_entry= tk.Entry(window1,width=14, bg="#183936", font=('Ariston Comic Demo Regular', 35), relief="flat")
    password_entry.configure(show="*")
    password_entry.place(x=776, y=555)


Main= tk.PhotoImage(file= r"C:/Users/willi/Images/Asset 15.png")
canvas= tk.Canvas(window,width=1920,height=1080)
canvas.create_image(0,0,anchor=tk.NW, image= Main)
canvas.pack()
signup_button=tk.Button(window,width=23, text="Sign Up!", font="CCDutchCourage2", fg="white", height=1, relief="flat", bg="#183936", command=createNewWindow)
signup_button.place(x=840, y=665)
username_entry= tk.Entry(window,width=14, bg="#183936", font=('Ariston Comic Demo Regular', 35), relief="flat")
username_entry.place(x=776, y=447)
password_entry= tk.Entry(window,width=14, bg="#183936", font=('Ariston Comic Demo Regular', 35), relief="flat")
password_entry.configure(show="*")
password_entry.place(x=776, y=555)

You are mistaken.你误会了。 Your program does indeed store a value in the username_info.txt file.您的程序确实在username_info.txt文件中存储了一个值。

The problem is, you got two variables named username_entry .问题是,您有两个名为username_entry的变量。 One is global (defined at the end of the script) and one is local (defined in createNewWindow() ).一个是全局的(在脚本末尾定义),一个是本地的(在createNewWindow()中定义)。 SignUp() accesses the globally defined one. SignUp()访问全局定义的。 This corresponds to the first tk.Entry element in the first window .这对应于第一个window 中的一个tk.Entry元素。 If you leave this element empty and only type in the user name in the second window, nothing will be stored.如果您将此元素留空并且仅在第二个 window 中键入用户名,则不会存储任何内容。

Also, you missed the line tk.mainloop() in your posted example.此外,您在发布的示例中错过了tk.mainloop()行。 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM