【tkinter模块】点击按钮输出输入框中的内容

import tkinter

# 创建主窗口
win = tkinter.Tk()

# 设置标题
win.title('111')

# 设置大小和位置,前两个x大小 后两个+位置
win.geometry('400x400+500+200')


def show():
    print(entry.get())


entry = tkinter.Entry(win)

entry.pack()

button = tkinter.Button(win, text='按钮', command=show)

button.pack()

# 进入消息循环
win.mainloop()

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用 `tkinter` 库的 `filedialog` 模块来实现这个功能。下面是一个简单的代码示例: ``` import tkinter as tk from tkinter import filedialog def get_file_path(): file_path = filedialog.askopenfilename() print("选择的文件路径为:", file_path) root = tk.Tk() root.title("选择文件") button = tk.Button(root, text="选择文件", command=get_file_path) button.pack() root.mainloop() ``` 运行这段代码后,用户将会看到一个简单的窗口,点击按钮可以弹出文件选择对话框,选择文件后将会返回文件的路径,并在控制台输出。 ### 回答2: 使用tkinter编写一个用户输入框按钮的简单程序,当用户点击按钮后,程序会弹出一个文件选择对话框,用户可以选择一个文件并返回该文件的路径。 首先,我们需要导入tkinter模块和filedialog模块。 ```python import tkinter as tk from tkinter import filedialog ``` 然后,创建一个简单的GUI窗口,并设置窗口的标题。 ```python window = tk.Tk() window.title("文件选择示例") ``` 接下来,定义一个函数`select_file()`,用于处理按钮被点击后的操作。 ```python def select_file(): filepath = filedialog.askopenfilename() print("选择的文件路径:", filepath) ``` 在函数`select_file()`,我们使用`askopenfilename()`方法弹出文件选择对话框,用户选择一个文件后,文件的路径将被保存在`filepath`变量。你可以根据需要对返回的文件路径进行处理,比如打印在命令行窗口上。 然后,创建一个按钮,并设置按钮的文本和命令。 ```python button = tk.Button(window, text="选择文件", command=select_file) button.pack() ``` 最后,开启主事件循环。 ```python window.mainloop() ``` 完整代码如下: ```python import tkinter as tk from tkinter import filedialog def select_file(): filepath = filedialog.askopenfilename() print("选择的文件路径:", filepath) window = tk.Tk() window.title("文件选择示例") button = tk.Button(window, text="选择文件", command=select_file) button.pack() window.mainloop() ``` 当你运行这个程序时,一个简单的GUI窗口将会打开,点击按钮后会弹出文件选择对话框,选择一个文件后,该文件的路径将会被打印在命令行窗口上。 ### 回答3: 要实现这个功能,首先需要导入tkinter模块,然后创建一个GUI窗口,添加一个用户输入框和一个按钮。当用户点击按钮后,可以打开文件选择对话框,让用户选择文件。最后,将选定的文件路径返回给用户。 以下是一个简单的示例代码: ```python import tkinter as tk from tkinter import filedialog def get_file_path(): file_path = filedialog.askopenfilename() # 打开文件选择对话框 entry_path.delete(0, tk.END) # 清空输入框内容 entry_path.insert(tk.END, file_path) # 在输入框显示选定的文件路径 # 创建GUI窗口 window = tk.Tk() # 添加用户输入框 entry_path = tk.Entry(window, width=50) entry_path.pack() # 添加按钮 button_browse = tk.Button(window, text="浏览", command=get_file_path) button_browse.pack() # 运行窗口 window.mainloop() ``` 以上代码,`get_file_path()`函数用于处理按钮的点击事件,在函数内使用`filedialog.askopenfilename()`方法打开文件选择对话框,并返回选定文件的路径。然后,清空用户输入框内容,将选定的文件路径插入到输入框。创建窗口的部分使用了tkinter提供的相关方法,如`tk.Tk()`创建窗口,`tk.Entry()`创建输入框,`tk.Button()`创建按钮等。最后使用`window.mainloop()`运行窗口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值