简体   繁体   中英

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. 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.

The problem is, you got two variables named username_entry . One is global (defined at the end of the script) and one is local (defined in createNewWindow() ). SignUp() accesses the globally defined one. This corresponds to the first tk.Entry element in the first window . If you leave this element empty and only type in the user name in the second window, nothing will be stored.

Also, you missed the line tk.mainloop() in your posted example. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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