首页 > 解决方案 > Changing grid position with a button in python

问题描述

I am trying to make the radio buttons change the position of the entry field (called assignment)

what i expected was for it to grid it next to the button but instead i get this error

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
    return self.func(*args)
  File "<string>", line 16, in <lambda>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2223, in grid_configure
    + self._options(cnf, kw))
_tkinter.TclError: bad window path name ".!application.!entry"`

the issue is on line 16 with the lambda function

ive tried making the variable in the function, i've also tried having it run exec.

here is the code

from tkinter import *
import random
class application(Frame):
    def __init__(self,master ):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()
    def create_widgets(self, ):
        assignment = Entry(self)

        for i in self.winfo_children():
            i.destroy()
        self.var = IntVar()
        for i in range(8):
            Radiobutton(self, text = ('class ' + str(i + 1)), variable = self.var, value = (i+1), command = lambda i = i: assignment.grid()).grid(row = i, column = 1)
        for i in range(8):
            exec('class' + str(i) + ' = Label(self, text = \'34\')\nclass' + str(i) + '.grid(row = '+str(i)+',column =  3)')

        print(self.var.get())

root = Tk()
root.title('dumb kid idiot test')
root.geometry('500x500')
app = application(root)
root.mainloop()

标签: pythontkinterradio-buttongrid-layout

解决方案


让我们看一下这段代码:

def create_widgets(self, ):
    assignment = Entry(self)

    for i in self.winfo_children():
        i.destroy()

您正在创建一个条目小部件,然后您几乎立即将其删除,因为它是self. 因此,以后尝试使用或修改小部件的任何代码都将失败,并显示您给出的确切错误。

如果您打算使用该条目,请不要删除它。您可以通过以下几种方式做到这一点:

  • 您可以在循环中添加显式检查,这样您就不会在条目小部件上调用 delete,
  • 不要循环遍历所有子级,而是将要销毁的小部件保存在一个列表中,然后遍历该列表而不是所有子级。

推荐阅读