如何在不儲存的情況下在 Python Tkinter 視窗中顯示影像/螢幕截圖?


Tkinter 是一個標準的 Python 庫,用於建立和開發基於 GUI 的應用程式。要顯示影像,我們使用 PIL 或 Pillow 庫。

假設我們想要建立一個應用程式,該應用程式將擷取視窗的螢幕截圖並在另一個視窗中顯示捕獲的影像。為了實現這一點,我們可以按照以下步驟操作:

  • 匯入所需的庫。

  • 建立一個通用的按鈕來擷取螢幕截圖。

  • 定義一個函式來擷取螢幕截圖。

  • 在給定的函式中,定義我們想要擷取螢幕截圖的 **座標** 和 **區域**。

  • 建立一個頂級視窗並在其中定義一個標籤影像。

  • 打包小部件並顯示輸出影像。

示例

# Import the required libraries
from tkinter import *
import pyautogui
from PIL import ImageTk, Image

# Create an instance of tknter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")


# Define a function to take the screenshot
def take_screenshot():
   x = 500
   y = 500
   # Take the screenshot in the given corrds
   im1 = pyautogui.screenshot(region=(x, y, 700, 300))

   # Create a toplevel window
   top = Toplevel(win)
   im1 = ImageTk.PhotoImage(im1)

   # Add the image in the label widget
   image1 = Label(top, image=im1)
   image1.image = im1
   image1.place(x=0, y=0)

Button(win, text='Take ScreenShot', command=take_screenshot).pack(padx=10, pady=10)

win.mainloop()

輸出

執行程式碼時,它將顯示一個帶有擷取螢幕截圖按鈕的視窗。

現在,單擊“擷取螢幕截圖”按鈕,它將捕獲大小為 700 畫素寬和 300 畫素高的螢幕,起始座標為 (x=500, y=500)。

更新於:2021年8月6日

瀏覽量 1K+

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告