V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
RayChiang
V2EX  ›  Python

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

  •  
  •   RayChiang · 2019-01-22 14:33:13 +08:00 · 1277 次点击
    这是一个创建于 1914 天前的主题,其中的信息可能已经有所发展或是发生改变。
    语言环境 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 还是挺麻烦的,希望能有大神设计一个解决方案。
    RayChiang
        1
    RayChiang  
    OP
       2019-01-22 15:56:38 +08:00
    问题解决了:combobox.bind('<Button-1>', self.set)
    改成 combobox.bind('<<ComboboxSelected>>', self.set)
    wersonliu9527
        2
    wersonliu9527  
       2019-01-22 16:34:56 +08:00
    eric6+pyqt5 可以拖控件造界面,生成插槽函数
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2538 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:21 · PVG 09:21 · LAX 18:21 · JFK 21:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.