只要條目為 1 或 2,我就嘗試運行此函式。但在第一個有效輸入(1 或 2)之后,第二個輸入不執行任何操作,似乎卡在回圈中
(該函式列印所選檔案名 輸入編號)
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # there's no need to open the full GUI
def my_filebrowser(command):
filename = askopenfilename()
print(filename, command)
while True:
command = int(input('enter command: '))
if command == 1:
my_filebrowser(command)
elif command == 2:
my_filebrowser(command)
else:
break
我應該如何更改代碼以多次使用 tkinter 檔案瀏覽器(askopenfilename() 函式)?
uj5u.com熱心網友回復:
您可以簡單地創建和銷毀根視窗來實作這一點,但這不是一種高性能方法。
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def my_filebrowser(command):
root = Tk(); root.withdraw()
filename = askopenfilename()
print(filename, command)
root.destroy()
while True:
command = int(input('enter command: '))
if command == 1:
my_filebrowser(command)
elif command == 2:
my_filebrowser(command)
else:
break
您可以修改此代碼以使檔案對話框位于螢屏的前面和中間。我還為透明度添加了 alpha,您甚至不會注意到會發生什么:
def my_filebrowser(command):
root = Tk(); root.attributes('-alpha',0.01)
root.attributes('-topmost',True)
root.tk.eval(f'tk::PlaceWindow {root._w} center')
root.withdraw()
filename = askopenfilename()
root.destroy()
print(filename, command)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369266.html
