Raj*_*hta -2 python tkinter python-3.x
问题:
我有一个 for 循环,它将文本添加到文本框。我想要一个按钮位于文本之后、每次迭代在文本框中结束之前的最右侧。
另外,是否可以将某种标签(即其之前的文本)分配给按钮?因此,对于每次迭代,按钮都会调用一个函数并在其之前传递文本。
预期图像:
您可以使用制表位强制某些内容与右边距对齐。唯一的技巧是,每当调整窗口大小时,您都需要重新计算制表位。您可以通过绑定到<Configure>事件来做到这一点。当您将窗口紧接在制表符之后和换行符之前放置时,它将右对齐。
您可以将 lambda 函数与按钮关联,以便定义要发送到回调的数据。
这是一个简单的例子:
import tkinter as tk
def reset_tabs(event):
'''Add a tabstop at the right edge of the widget'''
right_margin = event.width - 8
if right_margin <= 0: return
tabs = (right_margin, "right")
event.widget.configure(tabs=tabs)
def callback(text):
print("you clicked {}".format(text))
root = tk.Tk()
text = tk.Text(root)
text.pack(fill="both", expand=True)
text.bind("<Configure>", reset_tabs)
for i in range(10):
item = "this is item {}".format(i+1)
text.insert("end", item + "\t\n")
button = tk.Button(text, text="x", padx=2, pady=2,
cursor="left_ptr",
bd=1, highlightthickness=0,
command = lambda text=item: callback(text))
text.window_create("end-2c", window=button)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
上面的代码会产生这样的窗口: