【发布时间】:2021-01-30 21:57:57
【问题描述】:
我无法从网格位置获取 tkinter 复选框按钮的开/关状态。在这个基本示例中,如果复选框已打开,我想打印文本,但我不断收到 checkbutton 对象没有属性 get 的错误,尽管当我单击其中一个复选框时,测试函数会打印“on”或“关”就好了。
import tkinter as tk
def gui(root):
root.geometry('150x150')
root.config(background='snow3')
for row in range(5):
checkboxVar = tk.IntVar()
checkbox = tk.Checkbutton(root, text='', variable=checkboxVar, command= lambda status=checkboxVar: test(status=status))
checkbox.select()
checkbox.grid(row=row, column=1)
textbox = tk.Text(root, height=1, width=10)
textbox.grid(row=row, column=2)
saveBtn = tk.Button(root, text='Save', command=save)
saveBtn.grid(row=6, column=1)
def save():
for row in range(5):
print(root.grid_slaves(row=row, column=2)[0].get('1.0', 'end-1c'))
if root.grid_slaves(row=row, column=1)[0].get() == 1:
print(root.grid_slaves(row=row, column=2)[0].get('1.0', 'end-1c'))
def test(status):
if status.get() == 0:
print('OFF')
if status.get() == 1:
print('ON')
if __name__ == '__main__':
root = tk.Tk()
gui(root)
tk.mainloop()
AttributeError: 'Checkbutton' object has no attribute 'get'
【问题讨论】:
-
这里的错误意味着它所说的,要获得一个checkbutton的值,你必须使用
get()和它的variable。
标签: python python-3.x tkinter tk