首页 > 解决方案 > Python 3 和 GUI Tkinter 徽标插入

问题描述

import tkinter as tk
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename, asksaveasfilename

def get(name):
  if name in imagelist:
    if imagelist[name][1] is None:
      print('loading image:', name)
      imagelist[name][1] = PhotoImage(file=imagelist[name][0])
        return imagelist[name][1]
      return None

path = '.\logo.gif'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "right", fill = "both", expand = "yes")

def open_file():
    """Open a file for editing."""
    filepath = askopenfilename(
        filetypes=[("Python files", "*.py"), ("All Files", "*.*")]
    )
    if not filepath:
        return
    txt_edit.delete(1.0, tk.END)
    with open(filepath, "r") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Simple Text Editor - {filepath}")

def save_file():
    """Save the current file as a new file."""
    filepath = asksaveasfilename(
        defaultextension="py",
        filetypes=[("Python files", "*.py"), ("All Files", "*.*")],
    )
    if not filepath:
        return
    with open(filepath, "w") as output_file:
        text = txt_edit.get(1.0, tk.END)
        output_file.write(text)
    window.title(f"Simple Text Editor - {filepath}")

def runsomething():
          exec((open_file()).read()) 

window = tk.Tk()
window.title("Application")
window.rowconfigure(0, minsize=500, weight=1)
window.columnconfigure(2, minsize=500, weight=1)

window.configure(background='grey')

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Open", command=open_file)
btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file)
btn_close = tk.Button(fr_buttons, text="Close", command=quit)
btn_exec = tk.Button(fr_buttons, text="Execute", command=runsomething)

btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)
btn_close.grid(row=2, column=0, sticky="ew", padx=5)
btn_exec.grid(row=3, column=0, sticky="ew", padx=5)
fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")

window.mainloop()

大家好,我是 python 和 tkinter 的新手。我正在尝试创建一个小应用程序,该应用程序将在右上角的灰色区域上有一些按钮和我的徽标。一切正常,但我在同一个窗口上插入徽标时遇到问题。我附加的代码是创建带有徽标的第二个窗口。有什么建议么 ?谢谢

标签: pythontkinter

解决方案


您可以通过删除创建新窗口(在def get和之间def open_file)的代码并将其添加到现有窗口中来获取同一窗口上的图像,如下所示:

txt_edit = tk.Text(window)
...
btn_exec = tk.Button(fr_buttons, text="Execute", command=runsomething)
img = ImageTk.PhotoImage(Image.open(".\logo.gif"))
lbl_logo = tk.Label(window, image = img)

btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
...
lbl_logo.grid(row = 0, column = 2, sticky = "nesw")

推荐阅读