我有这个代码,用值输入框创建一个gui。但是当我按下按钮时如何将其写入文件?
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
msg = messagebox
sdg = simpledialog
root = Tk()
w = Label(root, text="My Program")
w.pack()
msg.showinfo("welcome", "hi. ")
name = sdg.askstring("Name", "What is you name?")
age = sdg.askinteger("Age", "How old are you?")
答案 0 :(得分:0)
To write text to a file:
filename = "output.txt"
with open(filename, "w") as f:
f.write("{} - {}".format(name, age))
Check out the docs to learn about reading/writing text files.
Your code just shows dialogs, if you want to associate an action with a button, you'll need to run a main loop:
from tkinter import *
from tkinter import messagebox as msg
from tkinter import simpledialog as sdg
def btn_action():
msg.showinfo("welcome", "hi. ")
name = sdg.askstring("Name", "What is you name?")
age = sdg.askinteger("Age", "How old are you?")
filename = "output.txt"
with open(filename, "w") as f:
f.write("{} - {}".format(name, age))
root = Tk()
w = Label(root, text="My Program")
w.pack()
b = Button(root, text="Ask", command=btn_action)
b.pack()
root.mainloop()
See this tutorial to learn about tkinter.