python - 无法将命令绑定到按钮 Python 3.7
问题描述
我正在尝试获得一个按钮来在 Python 中做一些事情(使用 Tkinter)。我希望按钮获取组合框的当前选择并将其打印在屏幕上。
图形布局是 3 个独立的框架,但按钮和组合框都位于同一框架中(框架 #2)。
问题是我无法引用组合框。我正在阅读的错误:
Frame object has no attribute 'box'
Window object has no attribute 'box'
self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command= self.wipe(), text=...)
def wipe(self):
self.box.get()
或者我试过:
def wipe(self):
self.frame2.box.get()
目标是简单地从组合框中获取选定的选项。
这是产生相同错误的最小编码:
import tkinter as tk
from tkinter import ttk
class window():
def __init__(self,root):
self.frame=tk.Frame(root)
self.key=tk.Button(self.frame,text='PRESS ME',command=self.wipe())
self.box=ttk.Combobox(self.frame, options=['1','2','3'])
self.frame.pack()
self.key.pack()
self.box.pack()
def wipe(self):
self.box.get()
master=tk.Tk()
master.geometry('400x400')
app=window(master)
master.mainloop()
解决方案
我会在问题中添加标签“tkinter”。
尝试以下操作:
def wipe(self):
# code
self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command=wipe, text=...)
请注意以下事项:
- 我首先定义了擦除,然后才使用它。
- 我不太清楚你为什么要这样做
command=self.wipe()
,因为这里有两个问题。首先,您设置command
的结果self.wipe()
不是函数。第二,你没有定义self.wipe
,你定义了wipe
。 command=wipe
将command
关键字参数设置为函数wipe
自从我处理 tkinter 以来已经很久了,如果这不起作用,我将尝试通过再次检查文档来提供帮助。
推荐阅读
- tensorflow - DeepMind 的 Sonnet 提供了 Keras 没有的什么?
- ios - ios:共享扩展不允许我将 .txt 或 .csv 文件共享到我的应用程序
- apache - 通过 Apache 的 Openshift 路线
- java - 可以在 HttpServletResponse.sendRedirect() 中发送隐藏参数吗?
- css - 如何围绕同一原点旋转多个 SVG 重用元素?
- java - 将对象的 ArrayList 从一个活动移动到另一个活动。还有适配器问题
- amazon-ec2 - 无法在 ec2 实例中安装主管作为 ASP .Net Core 项目的服务管理器
- angular - HTML中的Angular Conditional不喜欢小于或大于符号
- botframework - 选择提示不会在 MS Bot 框架中呈现按钮
- java - 未使用 Webflux 生成 CSRF 令牌