Python label прозрачный фон

Блог

Главная — Вопросы по программированию — Как мне сделать фон метки tkinter прозрачным, чтобы был виден только текст?

Как мне сделать фон метки tkinter прозрачным, чтобы был виден только текст?

#python #user-interface #tkinter #label #transparent

#python #пользовательский интерфейс #tkinter #метка #прозрачный

Вопрос:

Я создаю приложение обратного отсчета для события, и мне удалось запустить все, кроме меток. Я не могу сделать их фон прозрачным, чтобы отображался только текст. Есть ли у меня способ сделать это?

 import datetime import tkinter as tk def round_time(dt, round_to): seconds = (dt - dt.min).seconds rounding = (seconds round_to / 2) // round_to * round_to return dt datetime.timedelta(0, rounding - seconds, -dt.microsecond) def ct(label): def count(): now = round_time(datetime.datetime.now(), round_to=1) eh = datetime.datetime(2019, 3, 31, 20, 30) tte = eh - now label.config(text=str(tte)) label.after(50, count) count() root = tk.Tk() root.title("Earth Hour Countdown!") now = round_time(datetime.datetime.now(), round_to=1) eh = datetime.datetime(2019, 3, 31, 20, 30) tte = eh - now frame = tk.Frame(root, bg="#486068") frame.place(relwidth=1, relheight=1) canvas = tk.Canvas(root, height=200, width=500) canvas.place(relwidth=1, relheight=1) bg_img = tk.PhotoImage(file="C:/Users/bmg/Desktop/eh1.gif") bg_label = tk.Label(canvas, image=bg_img) bg_label.place(relwidth=1, relheight=1) label_msg = tk.Label(root, text="Earth Hour Countdown:", font="MSGothic 50 bold", bg="black", fg="#652828", bd=1) label_msg.place(relx=0.035, rely=0.1) label_cd = tk.Label(root, text=str(tte), font="MSGothic 50 bold", bg="black", fg="#652828", bd=1) label_cd.place(relx=0.590, rely=0.1) ehtime_label = tk.Label(root, text=("Earth Hour:" eh.strftime("%d-%m-%Y %H:%M:%S")), font="MSGothic 50 bold", bg="black", fg="#652828", bd=1) ehtime_label.place(relx=0.13, rely=0.3) ct(label_cd) root.mainloop() 

Ответ №1:

Я не думаю, что вы можете сделать метку прозрачной.

Вы можете создать текст на холсте, хотя у этого текста по умолчанию нет фона:

 import datetime import tkinter as tk def round_time(dt, round_to): seconds = (dt - dt.min).seconds rounding = (seconds round_to / 2) // round_to * round_to return dt datetime.timedelta(0, rounding - seconds, -dt.microsecond) def ct(): def count(): now = round_time(datetime.datetime.now(), round_to=1) eh = datetime.datetime(2019, 3, 31, 20, 30) tte = eh - now canvas.itemconfig(label_cd, text=str(tte)) root.after(50, count) count() root = tk.Tk() root.title("Earth Hour Countdown!") now = round_time(datetime.datetime.now(), round_to=1) eh = datetime.datetime(2019, 3, 31, 20, 30) tte = eh - now canvas = tk.Canvas(root, height=360, width=1333) canvas.pack() bg_img = tk.PhotoImage(file="C:/Users/bmg/Desktop/eh1.gif") bg_label = canvas.create_image((0,0), image=bg_img, anchor=tk.N tk.W) label_msg = canvas.create_text((410, 120), text="Earth Hour Countdown:", font="MSGothic 50 bold", fill="#652828") label_cd = canvas.create_text((1030,120), text=str(tte), font="MSGothic 50 bold", fill="#652828") ehtime_label = canvas.create_text((650,240), text=("Earth Hour:" eh.strftime("%d-%m-%Y %H:%M:%S")), font="MSGothic 50 bold", fill="#652828") ct() root.mainloop() 

Обратите внимание, что это также требует некоторых изменений в размещении текста и способах его обновления. Я постарался максимально приблизить все к вашему примеру. Обратите внимание, что отсутствие фона для вашего текста может не обеспечить желаемой читаемости:

Читайте также:  Уменьшить полосу прокрутки css

введите описание изображения здесь

Комментарии:

1. Но как мне избавиться от белых границ вокруг изображения?

2. Добавить highlightthickness=0 к созданию холста

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » GUI
  • » Прозрачный background tkinter.Label

#1 Май 2, 2017 11:35:19

Прозрачный background tkinter.Label

Здравствуйте!
Подскажите пожалуйста, возможно ли сделать фон Label прозрачным или чтобы отображался только текст без фона?
Заранее благодарю.

#2 Май 2, 2017 12:47:21

Прозрачный background tkinter.Label

Неужели такая очевидная функция не предусмотрена? Странное это.

#3 Май 2, 2017 20:14:32

Прозрачный background tkinter.Label

Шта? правильно сформулированый вопрос способствует правильному ответу. пока непонятно что вы хотите. Лучше всего выложить запускабельный небольшой пример который демонстрирует вашу проблему.

#4 Май 4, 2017 12:43:17

Прозрачный background tkinter.Label

import tkinter as tk root = tk.Tk() root.geometry("600x400") bg = tk.PhotoImage(file='background.png') fon = tk.Label(image=bg) lab = tk.Label(text='Some Label') fon.grid() lab.grid(row=0, column=0, sticky=tk.NW) root.mainloop() 

#5 Май 4, 2017 16:21:55

Прозрачный background tkinter.Label

в такой реализации нету, tkinter.Label не имеет возможности установить прозрачныость фона, и допилить ХЗ как…
Везде советуют создавать канвас и по нему рисовать текст. Примерно вот так..

import tkinter as tk root = tk.Tk() c = tk.Canvas(width=600, height=400) c.pack() bg = tk.PhotoImage(file="postthumb-3-600x400.gif") c.create_image(300, 200, image=bg) lab = c.create_text(40, 10, text="Some Text. ", fill="Black") #c.coords(lab, 100, 100) #d=tk.Button(text="Click") #d.place(x= 90, y = 5) root.mainloop() 

Отредактировано PEHDOM (Май 4, 2017 16:22:25)

#6 Май 5, 2017 08:52:39

Прозрачный background tkinter.Label

Благодарю! И еще вопрос. Как в этом случае быть с флажками и радиокнопками? Есть ли возможность у них сделать прозрачный фон?

import tkinter as tk root = tk.Tk() root.geometry("600x400") bg = tk.PhotoImage(file='background.png') fon = tk.Label(image=bg) imv = tk.BooleanVar() che = tk.Checkbutton(root, variable=imv, onvalue=True, offvalue=False) imv.set(True) fon.grid() che.grid(row=0, column=0) #root.grid_columnconfigure(0, weight=1) root.mainloop() 

#7 Май 5, 2017 11:11:45

Прозрачный background tkinter.Label

Kemok
Благодарю! И еще вопрос. Как в этом случае быть с флажками и радиокнопками? Есть ли возможность у них сделать прозрачный фон?

нету, у ткинтера вообще с прозрачностью фона полная жопа, кроме прозрачности главного окна. Можно конечно нарисовать свои катринки для чекбаттона:

Читайте также:  Css background image cover width

убрать индикатор, а текст рисоваать поверх канваса через create_text, но всеравно вокруг катринки останеться серая рамочка:

import tkinter as tk root = tk.Tk() c = tk.Canvas(width=600, height=400) c.pack() bg = tk.PhotoImage(file="postthumb-3-600x400.gif") c.create_image(300, 200, image=bg) lab = c.create_text(40, 10, text="Some Text. ", fill="Black") imv = tk.BooleanVar() img_off = tk.PhotoImage(file="choff.gif") img_on = tk.PhotoImage(file="chon.gif") c.create_window(90, 10, window = tk.Checkbutton(root,indicatoron=False, image=img_off, selectimage=img_on, bd=0, selectcolor='')) root.mainloop() 

результат выглядит вот так

Отредактировано PEHDOM (Май 5, 2017 11:15:24)

Источник

Python label прозрачный фон

Python Forum

Python Forum

Make Label Text background (default color) transparent using tkinter in python

In reference to the earlier question, I am able to put a background image in the frame but now the major issue is that Label text is displaying with default background which I need to make transparent.

As per other references question tk.Canvas is the best option but is there any other way to make the background of text transparent using tk.Label, I use root.wm_attributes option but is making the Text transparent but not the Background Right now My display looks like as mentioned in the attachment.

import tkinter as tk from tkinter.filedialog import asksaveasfile from tkinter import messagebox from PIL import ImageTk, Image class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._frame = None self.ard_stat = read_json(JSON_PATH) self.switch_frame(StartPage) def switch_frame(self, frame_class): """Destroys current frame and replaces it with a new one.""" new_frame = frame_class(self) if self._frame is not None: self._frame.destroy() self._frame = new_frame self._frame.pack() class StartPage(tk.Frame): def loopCap(self): with open(JSON_PATH) as json_file1: self.data = json.load(json_file1) #print(self.data) if self.data['status'] == 'ACTIVE': #and (self.data['RH_img']!= 'null' or self.data['LH_img']!= 'null') a = self.text.set(self.data['status']) b = self.text1.set(self.data['RH_cnt']) c = self.text2.set(self.data['LH_cnt']) d = self.text3.set(self.data['barcode']) return self.text, self.text1, self.text2, self.text3, self.data def next_save(self): new_string = self.data['barcode'] new_folder = os.path.join(DATA_PATH,new_string) if os.path.exists(new_folder): #print("Folder Already Exists If Condition") tk.messagebox.showinfo("Info", "Folder Already Exists") else: #os.isfile(new_string) #print("Folder Already Exists") #tkMessageBox.showinfo("Info", "Folder Already Exists") #print("Make Directory Else Condition") json_dict = read_json(JSON_PATH) json_dict.update() dump_to_json(json_dict, JSON_PATH) os.mkdir(new_folder) for i in range(0,len(data)): folder_name = os.path.join(DATA_PATH, new_string, data[i]) os.mkdir(folder_name) files = [('All Files', '*.*'), ('Python Files', '*.py'), ('Text Document', '*.txt')] file = asksaveasfile(initialdir=folder_name, filetypes=files, defaultextension=files) json_dict = read_json(JSON_PATH) json_dict.update() dump_to_json(json_dict, JSON_PATH) self.master.after(500, self.loopCap) def __init__(self, master): super().__init__(master) self.master.geometry("1000x700+%d+%d" % (((self.master.winfo_screenwidth() / 2.) - (1280 / 2.)), ((self.master.winfo_screenheight() / 2.) - (720 / 2.)))) #self.master.state('zoomed') self.master.config(bg='powder blue') #myvar = self.master Frame1 = tk.Frame(self.master) Frame1.pack(side="bottom", fill="x", pady=10, anchor='w') Frame2 = tk.Frame(self.master) Frame2.pack(side="left", fill="both", pady=10, anchor='w', expand=True ) photo = tk.PhotoImage(file="images/BG.jpg") label = tk.Label(Frame2, image=photo) label.image = photo label.place(x=0, y=0) tk.Label(Frame2, text=' Decal Check ', font=('arial', 25, 'bold'), bg='powder blue', fg='black', anchor='w').grid(column=0,pady=2) b = tk.Button(Frame2, text="Add New Files", command= self.next_save) b.grid(row=11, column=1, pady=5, sticky='w') self.master.after(500, self.loopCap) if __name__ == "__main__": app = SampleApp() app.mainloop()

Источник

Читайте также:  Flex css высота элемента

Прозрачный Label в tkinter

Нужно одно изображение (png формат с прозрачным фоном) наложить на другое. Делаю так, но прозрачный фон забивается стандартными серыми пикселями, а нужно чтобы они оставались прозрачными и из под них пробивался фон. Можно ли это как-то осуществить?

import tkinter from PIL import Image, ImageTk win = tkinter.Tk() img_1 = Image.open('square.png') img_photo1 = ImageTk.PhotoImage(img_1) img_2 = Image.open('circle.png') img_photo2 = ImageTk.PhotoImage(img_2) square_label = tkinter.Label(win, image=img_photo1) square_label.place(x=0, y=0) sircle_label = tkinter.Label(win, image=img_photo2) sircle_label.place(x=0, y=0) win.mainloop() 

Получается так

А надо так

Ответы (1 шт):

Label как и другие Tk widgets не поддерживает прозрачность. Поэтому, если разместить одну Label поверх другой, то верхняя будет загораживать нижнюю.

Чтобы наложить картинку с прозрачным фоном на другую картинку в Tkinter, можно canvas использовать:

#!/usr/bin/env python3 import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, width=800, height=600, bg='white') image_sky = tk.PhotoImage(file='sky.png') image_sun = tk.PhotoImage(file='sun.png') canvas.create_image(0, 0, image=image_sky, anchor=tk.NW) canvas.create_image(0, 0, image=image_sun, anchor=tk.NW) canvas.pack() root.mainloop() 

Источник

Оцените статью