关于python Gui库tkinter中按钮绑定函数变量值无法获得的解决思路

众所周知,Python的Gui组件向来都不是很好用。在使用Python原生GUI库tkinter的时候,遇到了一些非常抓马的事情。调用按钮组件的时候,按钮执行后的变量值获取不到。如下列例子所示:

import tkinter as tk
from tkinter import filedialog

d = {'path': ''}

def getfile():
    path = filedialog.askopenfilename()
    fpath.set(path)
    print(path)
    d['path'] = path


root = tk.Tk()
root.title('获得按钮函数变量')

# 设置窗口
# screenheight 屏幕高度
screenheight = root.winfo_screenheight()
# screenwidth 屏幕宽度
screenwidth = root.winfo_screenwidth()
# 窗口高度
height = 600
# 窗口宽度
width = 800
# x tkinter窗口距离屏幕左边距离
x = round((screenwidth - width) / 2)
# y tkinter窗口距离屏幕上边距离
y = round((screenheight - height) / 2)
size = '{}x{}+{}+{}'.format(width, height, x, y)
root.geometry(size)
fpath = tk.StringVar()

l1 = tk.Label(root, font=('黑体', 10), text='文件路径:')
l1.place(x=10, y=40)
t1 = tk.Entry(root, textvariable=fpath, width=40)
t1.place(x=110, y=39)
b1 = tk.Button(root, text='打开文件夹', command=lambda: getfile())
b1.place(x=400, y=35)

print('输出框的值:',t1.get())
print(d)
root.mainloop()

print(d)

输出结果为:

输出框的值:
{'path': ''}
C:/Users/ASUS/Desktop/data.xlsx
{'path': 'C:/Users/ASUS/Desktop/data.xlsx'}

这个例子将文件的路径输出到t1组件,可以看到,无论是用字典保存还是用get方法获得Entry框的数据都无法成功拿到路径。但是在mainloop()结束后,字典的 赋值成功了。

看到这种结果,内心其实是非常崩溃的。这意味着只有当关闭输出框之后才可以获得变量值,如果涉及到后续在GUI中需要这些值的操作就无法进行,那我要这GUI有何用。

但是在按钮绑定的函数中,可以发现虽然赋值没有成功,但是print成功打印输出。于是我想到可在按钮函数中新建一个txt文本来存储变量值,这样执行其他操作时就通过读取txt文件来读取变量值。如下所示:

import tkinter as tk
from tkinter import filedialog


def getfile():
    path = filedialog.askopenfilename()
    fpath.set(path)
    with open('tmp_path.txt', 'w', encoding='utf-8') as f:
        f.write(path)


def getpath():
    with open('tmp_path.txt', 'r', encoding='utf-8') as f:
        print(f.read())


root = tk.Tk()
root.title('获得按钮函数变量')

# 设置窗口
# screenheight 屏幕高度
screenheight = root.winfo_screenheight()
# screenwidth 屏幕宽度
screenwidth = root.winfo_screenwidth()
# 窗口高度
height = 600
# 窗口宽度
width = 800
# x tkinter窗口距离屏幕左边距离
x = round((screenwidth - width) / 2)
# y tkinter窗口距离屏幕上边距离
y = round((screenheight - height) / 2)
size = '{}x{}+{}+{}'.format(width, height, x, y)
root.geometry(size)
fpath = tk.StringVar()

l1 = tk.Label(root, font=('黑体', 10), text='文件路径:')
l1.place(x=10, y=40)
t1 = tk.Entry(root, textvariable=fpath, width=40)
t1.place(x=110, y=39)
b1 = tk.Button(root, text='打开文件夹', command=lambda: getfile())
b1.place(x=400, y=35)
b2 = tk.Button(root, text='输出路径值', command=lambda: getpath())
b2.place(x=400, y=75)

root.mainloop()

输出结果为:

C:/Users/ASUS/Desktop/data.xlsx

由此可见,可以通过外部文件来存储按钮绑定函数中的变量值,当然文件格式不限于txt,也可以建立json文件来一个文件存储多个变量值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值