我在Ubuntu上用Python编写程序,从文件夹导入文件然后单击左键单击以突出显示文件名,单击“删除”键盘按钮以删除该突出显示的文件
单击即可正常工作 但是当我按下删除按钮时,它不起作用并开始删除完全没有必要的文件名字符。
我在按键盘上的“删除”按钮时尝试添加多功能?
如何在Python中使用“删除”按钮和IF ... THEN语句?
import subprocess,os
from Tkinter import *
def text_click_callback(event):
# an event to highlight a line when single click is done
line_no = event.widget.index("@%s,%s linestart" % (event.x, event.y))
line_end = event.widget.index("%s lineend" % line_no)
event.widget.tag_remove("highlight", 1.0, "end")
event.widget.tag_add("highlight", line_no, line_end)
event.widget.tag_configure("highlight", background="yellow")
the_text = event.widget.get(line_no, line_end)
tex.tag_bind(the_text, "<Delete>", lambda event, the_text1 = path+'/'+the_text: os.remove(the_text1))
def viewFile():
tex.delete('1.0', END)
for f in os.listdir(path):
linkname="link-" + f
tex.insert(END,f + "\n", linkname)
tex.tag_configure(linkname, foreground="blue", underline=True)
tex.tag_bind(linkname, "<Button-1>", text_click_callback ) # highlight a line
if __name__ == '__main__':
root = Tk()
step = LabelFrame(root,text="FILE MANAGER", font = "Arial 20 bold italic")
step.grid(row=1, columnspan=7, sticky='W',padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="ViewFile", font = "Arial 8 bold italic", activebackground="turquoise", width=30, height=5, command=viewFile).grid (row= 6, column =3)
Button(step, text="Exit", font = "Arial 8 bold italic", activebackground="turquoise", width=20, height=5, command=root.quit).grid (row= 6, column =5)
tex = Text(master=root) # TextBox For Displaying File Information
scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
scr.grid(row=8, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=8, column=1, sticky=E)
tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))
global process
path = os.path.expanduser("/tmp") # Define path To play, delete, or rename video
root.mainloop()
答案 0 :(得分:0)
不要使用tag_bind
。使用普通的bind
方法。然后,不是传入数据,而是对所选文件名进行绑定函数查询。如果绑定函数返回字符串"break"
,它将阻止默认绑定工作(删除字符的原因)。
听起来你最好不要使用列表框小部件,如果你所做的只是给用户一个要选择的项目列表。它将需要更少的代码,并且不受文本小部件提供的您可能不想要的其他行为的影响。
示例:
def deleteHighlightedFile(event):
text = event.widget.get("highlight.first", "highlight.last")
print "selected file:", text
return "break"
...
tex = Text(master=root)
tex.bind("<Delete>", deleteHighlightedFile)