Sorununuz, VLC'nin Tkinter Canvas üzerine video oynatırken, Canvas'ta yer alan Stop ve Download butonlarının videonun arkasında kalmasından kaynaklanıyor. Bu, VLC'nin video çıktısını Canvas'ın arka planına çizmesi nedeniyle meydana gelir. Çözüm olarak, butonları video üzerinde görünür tutmak için butonların Canvas'ta video oynatıldıktan sonra tekrar öne getirilmesi gerekmektedir.
Aşağıda, bu sorunu çözen tam kodu bulabilirsiniz. add_image fonksiyonunda yapılan değişikliklerle, Stop ve Download butonlarının video üzerinde kalması sağlanmıştır.
Değişiklikler:
buttons_window_id adlı bir değişken ekleyerek butonların Canvas'taki window ID'sini sakladık.
toggle_video fonksiyonunu güncelleyerek video oynatıldığında butonların öne getirilmesini sağladık.
Tam Kod:
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import requests
import threading
import io
import os
import vlc # python-vlc eklenmiş
import time # Gecikme kontrolü için eklenmiş
from pynput import mouse # Pynput eklenmiş kısmı
# Video Player Class
class VideoPlayer:
def __init__(self, canvas, video_url, vlc_instance, play_stop_button):
"""
:param canvas: Tkinter Canvas içinde video ve kontrol butonlarının yer alacağı alan.
:param video_url: Video URL'si.
:param vlc_instance: Paylaşılan VLC Instance objesi.
:param play_stop_button: Play/Stop butonu.
"""
self.canvas = canvas
self.video_url = video_url
self.vlc_instance = vlc_instance
self.play_stop_button = play_stop_button
self.player = self.vlc_instance.media_player_new()
self.playing = False
self.video_handle = None # Video DOM element id
self.control_elements = {} # To store control elements if needed
def start_video(self):
if self.playing:
return
self.playing = True
# Pencere ID'sini al ve VLC'ye bağla
if os.name == "nt":
self.video_handle = self.canvas.winfo_id()
self.player.set_hwnd(self.video_handle)
elif os.name == "posix":
self.video_handle = self.canvas.winfo_id()
self.player.set_xwindow(self.video_handle)
else:
# MacOS için gerekli yöntemler (kullanıcı tarafından tamamlanmalı)
pass
# Medyayı ayarla
media = self.vlc_instance.media_new(self.video_url)
self.player.set_media(media)
# VLC'ye video alanını tamamen doldurmasını söyle
self.player.video_set_aspect_ratio("") # Oran korumasını devre dışı bırak
self.player.video_set_scale(0) # Ölçeklendirmeyi normal yap
# Video oynat
self.player.play()
# Buton metnini güncelle
self.play_stop_button.config(text="■")
def stop_video(self):
if not self.playing:
return
self.playing = False
self.player.stop()
# Buton metnini güncelle
self.play_stop_button.config(text="▶")
# Video İndirme Fonksiyonu (Asenkron)
def download_video(video_url, code, button):
if not video_url:
print(f"Video URL bulunamadı (Code: {code}).")
return
def download():
try:
response = requests.get(video_url, stream=True)
response.raise_for_status()
# 'videos' klasörünü oluştur
if not os.path.exists('videos'):
os.makedirs('videos')
# Dosya adını code kullanarak oluştur
file_name = f"{code}.mp4"
save_path = os.path.join('videos', file_name)
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print(f"Video başarıyla indirildi: {save_path}")
# Download butonunu yeşil yap ve disable et
button.after(0, lambda: button.config(style='Green.TButton', text="Downloaded", state="disabled"))
except Exception as e:
print(f"Video indirirken hata oluştu (Code: {code}): {e}")
button.after(0, lambda: messagebox.showerror("İndirme Hatası", f"Video indirilemedi: {e}"))
# Download işlemini ayrı thread'de başlat
threading.Thread(target=download, daemon=True).start()
# Veri Çekme Fonksiyonu
def fetch_data(callback):
headers = {
'user-agent': 'Instagram 146.0.0.27.125 (iPhone12,1; iOS 13_3; en_US; en-US; scale=2.00; 1656x3584; 190542906)'
}
data = {
'target_user_id': '55408673825',
'page_size': '12'
}
try:
response = requests.post('https://i.instagram.com/api/v1/clips/user/', headers=headers, data=data)
response.raise_for_status() # HTTP hatalarını yakalamak için
response_data = response.json()
max_id = response_data['paging_info'].get('max_id')
print("Max ID:", max_id)
items = []
for i in range(len(response_data.get("items", []))):
try:
media = response_data["items"][i]["media"]
image_versions = media["image_versions2"]
candidates = image_versions.get("candidates", [])
# 'candidates' bir liste ise ilk öğeyi al
if isinstance(candidates, list) and len(candidates) > 0:
candidates_frame = candidates[0].get("url")
if candidates_frame:
# Video URL'sini de al
video_versions = media.get("video_versions", [])
if video_versions and isinstance(video_versions, list):
video_url = video_versions[0].get("url")
else:
video_url = None
# 'code' değerini al
code = media.get("code", f"video_{i}")
items.append({
"image_url": candidates_frame,
"video_url": video_url,
"code": code
})
else:
# 'candidates' doğrudan bir sözlük ise
candidates_frame = image_versions["candidates"][0]["url"]
# Video URL'sini de al
video_versions = media.get("video_versions", [])
if video_versions and isinstance(video_versions, list):
video_url = video_versions[0].get("url")
else:
video_url = None
# 'code' değerini al
code = media.get("code", f"video_{i}")
items.append({
"image_url": candidates_frame,
"video_url": video_url,
"code": code
})
except (KeyError, IndexError, TypeError) as e:
print(f"Item {i} için veri alınırken hata oluştu:", e)
callback(items)
except Exception as e:
print("Veri çekerken hata oluştu:", e)
callback([]) # Hata durumunda boş liste döndür
# Görüntüleri İndirme ve Ekleme Fonksiyonu
def load_images(items, frame, vlc_instance, columns=4, image_size=(600, 900)):
def download_and_display(index, item):
image_url = item["image_url"]
video_url = item["video_url"]
code = item["code"]
try:
img_response = requests.get(image_url)
img_response.raise_for_status()
img_data = img_response.content
image = Image.open(io.BytesIO(img_data))
image = image.resize(image_size, Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(image)
# Tkinter sadece ana thread'de güncellenebilir, bu yüzden after kullanıyoruz
def add_image():
row = index // columns
col = index % columns
# Image Frame oluştur
image_frame = ttk.Frame(frame, relief="raised", borderwidth=2)
image_frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
frame.grid_rowconfigure(row, weight=1)
frame.grid_columnconfigure(col, weight=1)
# Canvas oluştur
canvas = tk.Canvas(image_frame, width=image_size[0], height=image_size[1], highlightthickness=0)
canvas.grid(row=0, column=0, sticky="nsew")
image_frame.grid_rowconfigure(0, weight=1)
image_frame.grid_columnconfigure(0, weight=1)
# Görüntüyü Canvas'a ekle
canvas.create_image(0, 0, anchor="nw", image=photo)
canvas.image = photo # Referansı saklamak önemli
# Butonlar için Frame oluştur
buttons_frame = ttk.Frame(canvas)
# Create a window on the canvas for the buttons_frame at top-right
buttons_window_id = canvas.create_window(image_size[0], 0, anchor="ne", window=buttons_frame)
# Play/Stop Butonu
play_stop_button = ttk.Button(buttons_frame, text="▶", width=3)
play_stop_button.pack(side="left", padx=(0, 5))
# Download Butonu
if video_url:
download_button = ttk.Button(buttons_frame, text="Download")
download_button.config(command=lambda b=download_button: download_video(video_url, code, b))
else:
download_button = ttk.Button(buttons_frame, text="Download", state="disabled")
download_button.pack(side="left")
# Video Player'ı saklamak için (sadece video varsa)
video_player = None
if video_url:
video_player = VideoPlayer(canvas, video_url, vlc_instance, play_stop_button)
def toggle_video():
nonlocal video_player
if video_player.playing:
video_player.stop_video()
else:
video_player.start_video()
# Butonların üstte kalmasını sağla
canvas.tag_raise(buttons_window_id)
# Buton metnini güncellemek yerine VideoPlayer sınıfında yapılıyor
play_stop_button.config(command=toggle_video)
frame.after(0, add_image)
except Exception as e:
print(f"Görüntü indirirken hata oluştu ({image_url}):", e)
def download_video_button_action(video_url, code, button):
# Butona referans geçiyoruz
download_video(video_url, code, button)
# Görüntüleri indirirken ve eklerken aynı anda işle
for idx, item in enumerate(items):
threading.Thread(target=download_and_display, args=(idx, item), daemon=True).start()
# Ana Uygulama Sınıfı
class ImageApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("Instagram Görselleri")
self.state('zoomed') # Pencereyi tam ekran yap (OS'a özgü)
self.bind("<F11>", self.toggle_fullscreen) # F11 ile tam ekran toggle
self.bind("<Escape>", self.exit_fullscreen) # Escape ile tam ekrandan çık
# Stil Tanımlamaları
self.style = ttk.Style()
self.style.configure('Green.TButton', foreground='white', background='#4CAF50') # Yeşil renk için stil
self.style.map('Green.TButton',
foreground=[('active', 'white')],
background=[('active', '#45a049')])
# Paylaşılan VLC instance, ses kapalı olarak başlatılıyor
self.vlc_instance = vlc.Instance('--no-xlib', '--no-audio') # '--no-audio' sesleri kapatır
# Scrollable frame oluşturma
container = ttk.Frame(self)
container.pack(fill="both", expand=True)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
self.scrollable_frame = ttk.Frame(canvas)
canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
self.scrollable_canvas = canvas # Canvas'ı erişilebilir kılmak için ekledik
self.scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
# Initialize debounce variables
self.last_scroll_time = 0
self.scroll_delay = 100 # milliseconds
# Bind mouse wheel scrolling using Pynput
self.start_mouse_listener(canvas)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Başlangıçta yükleme mesajı
self.loading_label = ttk.Label(self.scrollable_frame, text="Görseller yükleniyor...", font=("Arial", 16))
self.loading_label.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# Veri çekme işlemini başlat
threading.Thread(target=self.start_fetching, daemon=True).start()
def start_mouse_listener(self, canvas):
# Pynput ile global mouse tekerleği dinleyicisi oluşturma
def on_scroll(x, y, dx, dy):
current_time = time.time() * 1000 # current time in ms
if current_time - self.last_scroll_time < self.scroll_delay:
return # Debounce: ignore if within the delay time
self.last_scroll_time = current_time
# dy: Dikey kaydırma (pozitif: aşağı, negatif: yukarı)
if dy > 0:
direction = -1 # Aşağı kaydır
elif dy < 0:
direction = 1 # Yukarı kaydır
else:
direction = 0
if direction != 0:
# Tkinter main thread üzerinde çalışmalı
canvas.after(0, lambda: canvas.yview_scroll(direction, "units"))
def listen():
with mouse.Listener(on_scroll=on_scroll) as listener:
listener.join()
# Mouse listener'ı ayrı bir thread'de başlat
listener_thread = threading.Thread(target=listen, daemon=True)
listener_thread.start()
def toggle_fullscreen(self, event=None):
is_fullscreen = self.attributes("-fullscreen")
self.attributes("-fullscreen", not is_fullscreen)
def exit_fullscreen(self, event=None):
self.attributes("-fullscreen", False)
def start_fetching(self):
fetch_data(self.on_data_fetched)
def on_data_fetched(self, items):
# Yükleme mesajını kaldır
self.scrollable_frame.after(0, self.loading_label.destroy)
if not items:
# Eğer boşsa, kullanıcıya bilgi ver
info_label = ttk.Label(self.scrollable_frame, text="Hiç video bulunamadı veya veri çekilemedi.",
font=("Arial", 14))
info_label.grid(row=1, column=0, padx=10, pady=10)
return
# Görselleri yükle ve göster
load_images(items, self.scrollable_frame, self.vlc_instance, columns=4, image_size=(600, 900))
if __name__ == "__main__":
app = ImageApp()
app.mainloop()
Açıklamalar:
-
Butonların Öne Getirilmesi:
buttons_window_id değişkeni, butonların Canvas içindeki window ID'sini saklar.
toggle_video fonksiyonu, video oynatıldığında canvas.tag_raise(buttons_window_id) çağrısını yaparak butonları öne getirir. Bu, butonların video tarafından kapatılmasını engeller.
-
Play/Stop Butonunun Güncellenmesi:
play_stop_button.config çağrısı, butonun metnini güncelleyerek oynatma ve durdurma işlevlerini sağlar.
-
Thread Kullanımı:
- Görüntülerin ve videoların yüklenmesi işlemleri ayrı thread'lerde çalıştırılarak, ana GUI'nin donması engellenmiştir.
-
VLC Video Oynatma:
- VLC,
--no-xlib ve --no-audio parametreleri ile başlatılarak, ses olmadan ve GUI ile etkileşime girmeden video oynatılır.
Bu değişiklikler sayesinde, Play butonuna basıldığında video oynatılırken Stop ve Download butonları videonun arkasında kalmayacak ve her zaman görünür olacaktır. Bu, kullanıcı deneyimini iyileştirir ve kontrollerin kolay erişilebilir olmasını sağlar.