1

我使用 window_create 在 Text 元素中创建交互式按钮。按钮代表随机或静态值,我希望能够编译文本元素的内容并用它们各自的值替换按钮。但是,我找不到任何按钮的位置。

我试过self.text.get("1.0",tk.END)了,但它只返回文本,不包括按钮元素

按钮元素的创建方式如下:

btn_text = tk.StringVar()
value = StaticValue('static', btn_text, self.custom_val_veiwer, idx)
button = tk.Button(self.text, 
                        textvariable=btn_text, command=lambda v=value: 
                        self.veiw_custom_val(None, val=v))
btn_text.set('static')
self.custom_vals.append(value)
self.text.window_create(tk.INSERT, window=button)

编辑:如果您想重新创建问题,请使用:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.pack()

text.insert(tk.END, 'before button')

button = tk.Button(text, text='button')
text.window_create(tk.END, window=button)

text.insert(tk.END, 'after button')
print(text.get("1.0",tk.END))
root.mainloop()

注意按钮在文本字段中的显示方式,但没有打印出来

(输出是 before buttonafter button我想要类似的东西before button<button>after button或一个函数,它会告诉我在索引 y 处的 x 行有一个按钮)

4

1 回答 1

2

没有什么能提供你想要的东西,但只需要几行代码就可以得到点击按钮的索引。

我要做的是让按钮将对自身的引用作为命令的参数传递。这需要分两步制作按钮,因为您无法在创建按钮之前引用它。

button = tk.Button(text, text="button")
button.configure(command=lambda button=button: handle_click(button))

在按钮调用的函数中,您可以使用文本小部件dump命令获取所有窗口的列表,并从中找到按钮的索引。dump 命令将返回一个元组列表。每个元组都有一个键(在本例中为“window”)、窗口名称和窗口索引。您可以遍历该命令的结果以查找传递给函数的按钮的索引。

def handle_click(button):
    for (key, name, index) in text.dump("1.0", "end", window=True):
        if name == str(button):
            print("you clicked on the button at index {}".format(index))
            break

例子

这是一个添加几个按钮的人为示例。单击按钮将在标签中显示该按钮的索引。请注意,即使您手动编辑文本小部件以更改按钮的索引,它仍将继续工作。

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
label = tk.Label(root)
label.pack(side="top", fill="x")
text.pack(side="top", fill="both", expand=True)

def handle_click(button):
    for (key, name, index) in text.dump("1.0", "end", window=True):
        if name == str(button):
            label.configure(text="You clicked on the button at {}".format(index))
            break

for word in ("one", "two", "three", "four", "five"):
    text.insert("end", word + "\n")
    button = tk.Button(text, text="click me")
    button.configure(command=lambda button=button: handle_click(button))
    text.window_create("insert-1c", window=button)

tk.mainloop()
于 2019-05-10T19:06:32.760 回答