Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I seem to be having a problem with adding an image to my custom title bar and I can't seem to solve it. I tried to search the web but couldn't get the results I was looking for.

import tkinter as tkr
from tkinter import *
from tkinter.ttk import *
from PIL import Image

window = tkr.Tk()
window.geometry("1000x500")

window.overrideredirect(1)

title_bar = tkr.Frame(window, bg=Col_bg3, relief='raised', bd=0)

#Title Bar Buttons
close_button = tkr.Button(title_bar, text="?", bd=0, height=3, width=5)
minimise_button = tkr.Button(title_bar, text="-", bd=0, height=3, width=5)
maximise_button = tkr.Button(title_bar, text="min", bd=0, height=3, width=5)
menu_button = tkr.Button(title_bar, image=menu_image, bg=Col_bg3, fg=Col_fg1, highlightbackground=Col_bg4, bd=0)

menu_image = PhotoImage(title_bar, file="images/menu.png")

title_bar.pack(expand=0, fill="x")
close_button.pack(side=tkr.RIGHT)
maximise_button.pack(side=tkr.RIGHT)
minimise_button.pack(side=tkr.RIGHT)
menu_button.pack(side=tkr.LEFT, padx=(50,10))

window.mainloop()

Here is what the console gave me:

Traceback (most recent call last):
  File "[...]main.py", line 69, in <module>
    menu_button = tkr.Button(title_bar, image=menu_image, bg=Col_bg3, fg=Col_fg1, highlightbackground=Col_bg4, bd=0)
NameError: name 'menu_image' is not defined

Process finished with exit code 1

I'm still learning the language so I may have done it the incorrect way, but I've tried setting the variable as a global, set the variable to self. But I couldn't get it working. Does anyone might know how I could get this working?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
408 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your menu_bar object hasn't been initialised before you reference it in your menu_button object.

Try initialising it first.

#Title Bar Buttons
menu_image = PhotoImage(title_bar, file="images/menu.png")

close_button = tkr.Button(title_bar, text="?", bd=0, height=3, width=5)
minimise_button = tkr.Button(title_bar, text="-", bd=0, height=3, width=5)
maximise_button = tkr.Button(title_bar, text="min", bd=0, height=3, width=5)
menu_button = tkr.Button(title_bar, image=menu_image, bg=Col_bg3, fg=Col_fg1, highlightbackground=Col_bg4, bd=0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...