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

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

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

语言环境 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 还是挺麻烦的,希望能有大神设计一个解决方案。 ----------------------- 以下是精选回复-----------------------

答:问题解决了:combobox.bind('<Button-1>', self.set)
改成 combobox.bind('<<ComboboxSelected>>', self.set)
答:eric6+pyqt5 可以拖控件造界面,生成插槽函数

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 在面向对象中使用 tkinter 时的一个小问题

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情