鱼C论坛

 找回密码
 立即注册
查看: 10162|回复: 4

Tkinter 拖拽功能求助

[复制链接]
发表于 2022-7-30 23:28:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我用tkinter做了一个窗口,用treeview做了个文件浏览器,我现在想实现如下功能,可以把treeview中列出的文件拖扯出窗口,移动到指定的文件夹,并获取目标文件夹的路径,我用TkinterDND实现了这个功能,可以正常移动文件,但我无法获取文件位置,希望大神帮忙,谢谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-8-4 21:36:41 | 显示全部楼层
TkinterDND2 就可以很简单的实现。TkinterDND不清楚。
示例代码:
  1. # -*- coding: utf-8 -*-

  2. import os
  3. import platform
  4. from tkinterdnd2 import *
  5. try:
  6.     from Tkinter import *
  7.     from ScrolledText import ScrolledText
  8. except ImportError:
  9.     from tkinter import *
  10.     from tkinter.scrolledtext import ScrolledText

  11. root = TkinterDnD.Tk()
  12. root.withdraw()
  13. root.title('TkinterDnD demo')
  14. root.grid_rowconfigure(1, weight=1, minsize=250)
  15. root.grid_columnconfigure(0, weight=1, minsize=300)
  16. root.grid_columnconfigure(1, weight=1, minsize=300)

  17. def print_event_info(event):
  18.     print('\nAction:', event.action)
  19.     print('Supported actions:', event.actions)
  20.     print('Mouse button:', event.button)
  21.     print('Type codes:', event.codes)
  22.     print('Current type code:', event.code)
  23.     print('Common source types:', event.commonsourcetypes)
  24.     print('Common target types:', event.commontargettypes)
  25.     print('Data:', event.data)
  26.     print('Event name:', event.name)
  27.     print('Supported types:', event.types)
  28.     print('Modifier keys:', event.modifiers)
  29.     print('Supported source types:', event.supportedsourcetypes)
  30.     print('Operation type:', event.type)
  31.     print('Source types:', event.sourcetypes)
  32.     print('Supported target types:', event.supportedtargettypes)
  33.     print('Widget:', event.widget, '(type: %s)' % type(event.widget))
  34.     print('X:', event.x_root)
  35.     print('Y:', event.y_root, '\n')

  36. Label(root, text='Drag and drop files here:').grid(
  37.                     row=0, column=0, padx=10, pady=5)
  38. Label(root, text='Drag and drop text here:').grid(
  39.                     row=0, column=1, padx=10, pady=5)
  40. buttonbox = Frame(root)
  41. buttonbox.grid(row=2, column=0, columnspan=2, pady=5)
  42. Button(buttonbox, text='Quit', command=root.quit).pack(
  43.                     side=LEFT, padx=5)

  44. ##############################################################################
  45. ######   Basic demo window: a Listbox to drag & drop files                  ##
  46. ######   and a Text widget to drag & drop text                              ##
  47. ##############################################################################
  48. listbox = Listbox(root, name='dnd_demo_listbox',
  49.                     selectmode='extended', width=1, height=1)
  50. listbox.grid(row=1, column=0, padx=5, pady=5, sticky='news')
  51. text = Text(root, name='dnd_demo_text', wrap='word', undo=True, width=1, height=1)
  52. text.grid(row=1, column=1, pady=5, sticky='news')

  53. listbox.insert(END, os.path.abspath(__file__))
  54. info = 'TkinterDnD demo\nDetected versions:\n'
  55. info += '    Python: %s\n' % platform.python_version()
  56. info += '    Tk    : %f\n' % TkVersion
  57. info += '    Tkdnd : %s\n' % TkinterDnD.TkdndVersion
  58. info += 'Use mouse button 3 to drag hightlighted text from the text box.\n'
  59. text.insert(END, info)

  60. # Drop callbacks can be shared between the Listbox and Text;
  61. # according to the man page these callbacks must return an action type,
  62. # however they also seem to work without

  63. def drop_enter(event):
  64.     event.widget.focus_force()
  65.     print('Entering widget: %s' % event.widget)
  66.     #print_event_info(event)
  67.     return event.action

  68. def drop_position(event):
  69.     print('Position: x %d, y %d' %(event.x_root, event.y_root))
  70.     #print_event_info(event)
  71.     return event.action

  72. def drop_leave(event):
  73.     print('Leaving %s' % event.widget)
  74.     #print_event_info(event)
  75.     return event.action

  76. def drop(event):
  77.     if event.data:
  78.         print('Dropped data:\n', event.data)
  79.         #print_event_info(event)
  80.         if event.widget == listbox:
  81.             # event.data is a list of filenames as one string;
  82.             # if one of these filenames contains whitespace characters
  83.             # it is rather difficult to reliably tell where one filename
  84.             # ends and the next begins; the best bet appears to be
  85.             # to count on tkdnd's and tkinter's internal magic to handle
  86.             # such cases correctly; the following seems to work well
  87.             # at least with Windows and Gtk/X11
  88.             files = listbox.tk.splitlist(event.data)
  89.             for f in files:
  90.                 if os.path.exists(f):
  91.                     print('Dropped file: "%s"' % f)
  92.                     listbox.insert('end', f)
  93.                 else:
  94.                     print('Not dropping file "%s": file does not exist.' % f)
  95.         elif event.widget == text:
  96.             # calculate the mouse pointer's text index
  97.             bd = text['bd'] + text['highlightthickness']
  98.             x = event.x_root - text.winfo_rootx() - bd
  99.             y = event.y_root - text.winfo_rooty() - bd
  100.             index = text.index('@%d,%d' % (x,y))
  101.             text.insert(index, event.data)
  102.         else:
  103.             print('Error: reported event.widget not known')
  104.     return event.action

  105. # now make the Listbox and Text drop targets
  106. listbox.drop_target_register(DND_FILES, DND_TEXT)
  107. text.drop_target_register(DND_TEXT)

  108. for widget in (listbox, text):
  109.     widget.dnd_bind('<<DropEnter>>', drop_enter)
  110.     widget.dnd_bind('<<DropPosition>>', drop_position)
  111.     widget.dnd_bind('<<DropLeave>>', drop_leave)
  112.     widget.dnd_bind('<<Drop>>', drop)
  113.     #widget.dnd_bind('<<Drop:DND_Files>>', drop)
  114.     #widget.dnd_bind('<<Drop:DND_Text>>', drop)

  115. # define drag callbacks

  116. def drag_init_listbox(event):
  117.     print_event_info(event)
  118.     # use a tuple as file list, this should hopefully be handled gracefully
  119.     # by tkdnd and the drop targets like file managers or text editors
  120.     data = ()
  121.     if listbox.curselection():
  122.         data = tuple([listbox.get(i) for i in listbox.curselection()])
  123.         print('Dragging :', data)
  124.     # tuples can also be used to specify possible alternatives for
  125.     # action type and DnD type:
  126.     return ((ASK, COPY), (DND_FILES, DND_TEXT), data)

  127. def drag_init_text(event):
  128.     print_event_info(event)
  129.     # use a string if there is only a single text string to be dragged
  130.     data = ''
  131.     sel = text.tag_nextrange(SEL, '1.0')
  132.     if sel:
  133.         data = text.get(*sel)
  134.         print('Dragging :\n', data)
  135.     # if there is only one possible alternative for action and DnD type
  136.     # we can also use strings here
  137.     return (COPY, DND_TEXT, data)

  138. def drag_end(event):
  139.     #print_event_info(event)
  140.     # this callback is not really necessary if it doesn't do anything useful
  141.     print('Drag ended for widget:', event.widget)

  142. # finally make the widgets a drag source

  143. listbox.drag_source_register(1, DND_TEXT, DND_FILES)
  144. text.drag_source_register(3, DND_TEXT)

  145. listbox.dnd_bind('<<DragInitCmd>>', drag_init_listbox)
  146. listbox.dnd_bind('<<DragEndCmd>>', drag_end)
  147. text.dnd_bind('<<DragInitCmd>>', drag_init_text)
  148. # skip the useless drag_end() binding for the text widget

  149. root.update_idletasks()
  150. root.deiconify()
  151. root.mainloop()


复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-8-6 21:51:46 | 显示全部楼层
多谢回复,我没说说清楚,我实际也是用的TkinterDND2,基本的拖拽功能也实现了,但是,我先获取我拖拽的目标路径,请问要如何做到.比如下图中高亮的文件,我可以把它拖拽到桌面上,但我要怎样在程序中得到我拖拽的目标文件夹是桌面呢?感谢
D:\Users\liangyc3\Desktop\新建文件夹 (4)\截图.jpg
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-8-6 21:52:44 | 显示全部楼层
D:\Users\liangyc3\Desktop\新建文件夹 (4)\截图.jpg
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-8-6 21:56:21 | 显示全部楼层
实在不好意思,我还不不会发送图片

D:\Users\liangyc3\Desktop\新建文件夹
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-23 17:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表