目录
1.文件打开和保存的选择框
2.选择或者输入对话框
1.文件打开和保存的选择框
tkinter.filedialog 模块中的 askopenfilename 函数和 asksaveasfilename 函数来显示文件打开和保存的选择框。
这两个函数的作用都是返回一个文件名。如果选择了一个文件,则会返回文件的绝对路径,如果取消了选择,则返回空字符串
前者用来读时的 filename,后者用来写时保存的 filename。
选择文件例子
from tkinter.filedialog import askopenfilename# 弹出文件选择对话框选择一个文件
read_file_name = askopenfilename()
if read_file_name != '':print("you can read from " + read_file_name)file1 = open(read_file_name, "r", encoding="utf-8")s = file1.read()print(s)
else:print("你未选择一个文件")
手动选择文件的例子
from tkinter.filedialog import asksaveasfilename# 弹出文件选择对话框选择保存文件
write_file_name = asksaveasfilename()
if write_file_name != "":print("you can write data to " + write_file_name)with open(write_file_name, "w", encoding="utf-8") as file:file.write("你好中国")
else:print("你未选择一个文件")
2.选择或者输入对话框
用途:
- 显示特定消息警告
-
提示用户输入数字和字符串
import tkinter.messagebox
import tkinter.simpledialog
import tkinter.colorchooser# 显示特定信息或警告
tkinter.messagebox.showinfo("对话框名字,它在对话框左上角", "对话框中间的内容")
tkinter.messagebox.showwarning("showwarning", "This is a warning")
tkinter.messagebox.showerror("showerror", "This is an error")# 提示用户进行选择,并获取值
isYes = tkinter.messagebox.askyesno("askyesno", "Contiue ?")
print(isYes) # True 或者 False
isOk = tkinter.messagebox.askokcancel("askokcancel", "OK ?")
print(isOk) # True 或者 False
isYesNoCancel = tkinter.messagebox.askyesnocancel("askyesnocancel", "Yes, No, Cancel ?")
print(isYesNoCancel) # True 或者 False 或者 None# 提示用户进行输入,并获取值
name = tkinter.simpledialog.askstring("askstring", "Enter your name")
print(name) # OK返回输入的内容,取消返回None,
age = tkinter.simpledialog.askinteger("askinteger", "Enter your age")
print(age) # OK返回输入的内容,输入非整数会报错,会让其重新输入,取消返回None,
weight = tkinter.simpledialog.askfloat("askfloat", "Enter your weight")
print(weight)
end