在面向对象中使用 tkinter 时的一个小问题

2019-01-22 14:33:13 +08:00
 RayChiang
语言环境 3.6,tkinter 是 python3.x 内置的一个 GUI 包
import tkinter
from tkinter import ttk

win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50")

cv = tkinter.StringVar()
com = ttk.Combobox(win, textvariable=cv)
com.pack()

com["value"] = ("黑龙江", "吉林", "辽宁")
com.current(0)

def func(event):
print(cv.get())

com.bind("<<ComboboxSelected>>", func)
win.mainloop()
上面这段代码时网上对 combobox 下拉菜单的一个实例,运行时点选下拉键再点击选项就会 print 那个选项的值。

而我在 class 中使用这个 bind 方法就会出现一个令人意外的 bug。
from tkinter import *
from tkinter.ttk import *


class Test(object):
def __init__(self):
self.window = Tk()
self.window.geometry("100x100+500+150")
self.value = StringVar()

def set(self, event):
print(self.value.get())

def pr(self):
print(self.value)

def start(self):
menu = Menu(self.window)
self.window.config(menu=menu)
combobox = Combobox(self.window, width=12, textvariable=self.value, state='readonly')
combobox["value"] = ("1", "2", "3", "4")
combobox.current(0)
combobox.place(relx=0, rely=0, x=10, y=30)
combobox.bind('<Button-1>', self.set)
self.window.mainloop()


if __name__ == '__main__':
run = Test()
run.start()


可能是因为我需要 print 的参数在 class 内部已经定义过了,所以点击下拉按钮时就会直接 print 出值,点击选项反而不会有结果。再次点击下拉按钮则会 print 上一次选择的值。
由于我需要记录这个值来用到其他函数中,所以这个 bug 还是挺麻烦的,希望能有大神设计一个解决方案。
1291 次点击
所在节点    Python
2 条回复
RayChiang
2019-01-22 15:56:38 +08:00
问题解决了:combobox.bind('<Button-1>', self.set)
改成 combobox.bind('<<ComboboxSelected>>', self.set)
wersonliu9527
2019-01-22 16:34:56 +08:00
eric6+pyqt5 可以拖控件造界面,生成插槽函数

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/529463

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX