【问题标题】:Outputting text to file Tkinter将文本输出到文件 Tkinter
【发布时间】:2020-04-06 21:41:53
【问题描述】:

当我要求它输出输入框到文件时,它什么也没做,因为我是 python 新手,所以我有点卡住了,我知道这是一个简单的问题,但我不太确定如何修理它。请帮忙。

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)

【问题讨论】:

  • 当你说它“什么都不做”时,你能更具体一点吗?如果您的代码完全如上,那么它不会执行任何操作,因为您错过了对mainloop() 的调用。底部需要window.mainloop()

标签: python file tkinter


【解决方案1】:

你错了。您的程序确实在username_info.txt 文件中存储了一个值。

问题是,您有两个名为username_entry 的变量。一种是全局的(在脚本末尾定义),一种是本地的(在createNewWindow() 中定义)。 SignUp() 访问全局定义的。这对应于 第一个窗口 中的 first tk.Entry 元素。如果您将此元素留空并仅在第二个窗口中输入用户名,则不会存储任何内容。

另外,您在发布的示例中错过了tk.mainloop() 行。 :)

【讨论】:

  • 如果此回复解决了您的问题,也请接受此作为正确答案。
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
相关资源
最近更新 更多