是否有任何像這樣作業的 GUI 程式 - 單擊 GUI 中的按鈕,它確實啟動了一些 python 代碼行或多行,我想到了 tkinter,但我沒有找到讓它啟動一些 python 代碼的選項,或者有嗎?Upd - 在終端代碼中使用代碼太復雜了,所以我需要 GUI。
uj5u.com熱心網友回復:
有幾種方法可以運行 python 代碼,它在 OP 中是必需的 - :
使用
execoreval動態運行 python 代碼(注意:這不會回傳輸出,而是直接運行代碼,就像它是普通代碼一樣。),還請注意,通常應避免使用execand ,eval但必須在此處提及可能的方式。exec(object, globals, locals) eval(expression[, globals[, locals]])啟動終端視窗(使用
os.systemos 模塊的方法)并使用pyautogui鍵入并運行執行給定 python 腳本的命令,當單擊按鈕時(注意:使用此方法,您也只能看到輸出腳本但不獲取它。)# required imports import os, pyautogui import tkinter as tk from tkinter import filedialog root = tk.Tk() # initializing the tkinter window. def ask_for_running_file(event = None) : filetypes = (("python files", '.py'), ("all files","*.*")) filename = filedialog.askopenfilename(initialdir = '/', title = "Select file", filetypes = filetypes) # Get the name of the python file to run. addr_command = 'start cmd /k "cd "' filename[ : filename.rindex('/')] # Command used to open the terminal run_command = ' python \"' filename[(filename.rindex('/') 1) : ] '\"' # The command to be typed in the terminal using pyautogui to execute the python script. os.system(addr_command) # Runs the command required to open the terminal window. pyautogui.write(run_command, interval = 0.25) # Writes the command required to execute the python script letter by letter. NOTE: The interval here can be adjusted as per use case. pyautogui.press('enter') # Pressing enter to execute the run command. return b1 = tk.Button(root, text = 'run file', command = ask_for_running_file) # The button that open a file dialog to choose #which file to run. b1.pack() # managing the geometry of the button. root.mainloop() # starting mainloop使用subprocess模塊獲取終端命令執行的輸出,然后使用 tkinter 或任何其他模塊(如果需要)顯示它。請注意,子流程模塊建議在大多數用例中使用run函式,因此下面提供的示例將僅涉及使用該函式。該檔案列出了每個引數的用法,并且可以根據需要進一步修改以下代碼。
result = subprocess.run(['python', '\"' script_name '\"'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell = True)
一旦確定了執行命令的方式,觸發它的按鈕和GUI就可以隨意設計在任何模塊中,例如方法2所示的功能也可以與任何其他GUI模塊的按鈕回呼函式一起使用!它應該可以正常作業,記住在函式中洗掉 tkinter filedialog 的使用可以保持不變。
筆記:
如果 pyautogui 在命令中鍵入時出現干擾,則第二種方法可能并不總是有效,因此它不適合需要后臺行程來解決問題的用例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439069.html
