Переключение окон с рамой - PullRequest
0 голосов
/ 11 марта 2020

Добрый вечер всем

Я занимаюсь разработкой программного обеспечения, знаю, что я новичок, я помогаю себе на Inte rnet, просматривая 2-3 видео. Мое программное обеспечение состоит из главного окна с 3 инструментами (Split / Fusion / Anti-Duplicate)

Я начал делать windows с (TopLevel), но это вызывает у меня много проблем, я выиграл ' t go в детали.

Сейчас я просто использую (Toplevel) для моего второго окна. Но я бы хотел, чтобы он переключился на фрейм:

И я просмотрел множество кодов, похожих на этот:

https://pythonprogramming.net/change-show-new-frame-tkinter/

Я пробовал много раз, я просто не могу адаптировать его к своему коду.


import os
import tkinter as tk
import webbrowser 
from tkinter import messagebox
import subprocess
import time
from tkinter import ttk
from tkinter.filedialog import askopenfilename

#----------------------------------------------------------

def OpenFile1():

   name1 = askopenfilename(initialdir="/",
                          filetypes =(("Text File", "*.txt"),("All Files","*.*")),
                          title = "Choose a file."
                          )
   print (name1)
   #Using try in case user types in unknown file or closes without choosing a file.
   try:
       with open(name1,'r') as UseFile:
           print(name1)
   except:
       print("No file exists")

#----------------------------------------------------------

class HoverButton(tk.Button):
   def __init__(self, master, **kw):
       tk.Button.__init__(self,master=master,**kw)
       self.defaultBackground = self["background"]
       self.bind("<Enter>", self.on_enter)
       self.bind("<Leave>", self.on_leave)

   def on_enter(self, e):
       self['background'] = self['activebackground']

   def on_leave(self, e):
       self['background'] = self.defaultBackground

#----------------------------------------------------------

def Anti_Duplicate():

   A_Duplicate = tk.Toplevel()
   A_Duplicate.resizable(width=False, height=False)
   screenn_x = int(A_Duplicate.winfo_screenwidth())
   A_Duplicate.config(background='#1c2028')
   screenn_y = int(A_Duplicate.winfo_screenheight()) 
   A_Duplicate.title("Anti-Duplicate v0.0.1")
   A_Duplicate.resizable(width=False, height=False)
   windowss_x = 570
   windowss_y = 340

   possX = (screenn_x // 2) - (windowss_x // 2)
   possY = (screenn_y // 2) - (windowss_y // 2)

   geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
   A_Duplicate.geometry(geoo)

   mainframe = tk.Frame(A_Duplicate, bg='#1c2028')
   mainframe.pack(side= "top", ipadx= 5, ipady= 5)

   bouton_1 = HoverButton(A_Duplicate, font=("Arial", 10), text="Back", background='#1c2028', fg='white',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='ridge', command= A_Duplicate.destroy)
   bouton_1.place(x=520, y=300)

   open_button = HoverButton(A_Duplicate, font=("Arial", 10), text="Ouvrir un fichier..", background='#1c2028', fg='white',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='ridge', command= OpenFile1)
   open_button.place(x=229.5, y=200)

   bouton_2 = tk.Button(A_Duplicate, font=("Arial", 10), text="Cet outil a pour but de supprimer les lignes en double d'un fichier texte.",  background='#202124', fg='#1195cf',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
   bouton_2.place(x=75.5, y=50)

   bouton_1 = tk.Button(mainframe, font=("Arial", 15), text="Anti-Duplicate", background='#202124', fg='#1195cf',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
   bouton_1.pack(padx= 5, pady=10, ipadx= 30)


#Couleur sur le bouton

def main_menu():

   main_screen = tk.Tk()
   main_screen.lift()
   screenn_x = int(main_screen.winfo_screenwidth())
   main_screen.config(background='#1c2028')
   screenn_y = int(main_screen.winfo_screenheight()) 
   main_screen.title("ComboKit v0.0.1")
   windowss_x = 570
   windowss_y = 340

   possX = (screenn_x // 2) - (windowss_x // 2)
   possY = (screenn_y // 2) - (windowss_y // 2)

   geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
   main_screen.geometry(geoo)

   mainframe = tk.Frame(main_screen, bg='#1c2028')
   mainframe.pack(side= "top", ipadx= 5, ipady= 5)

   bouton_1 = HoverButton(mainframe, font=("Arial", 15), text="Fusion", background='#1c2028', fg='white',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='ridge', command=None)
   bouton_1.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   bouton_2 = HoverButton(mainframe, font=("Arial", 15), text="Anti-Duplicate", background='#1c2028', fg='white',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='ridge', command=Anti_Duplicate)
   bouton_2.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   bouton_3 = HoverButton(mainframe, font=("Arial", 15), text="Split ", background='#1c2028', fg='white',  borderwidth=2, activebackground= '#202124', activeforeground='#1195cf', relief='ridge', command=None)
   bouton_3.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   main_screen.mainloop()

main_menu()

Большое спасибо людям, которые мне помогут!

1 Ответ

1 голос
/ 11 марта 2020

Всего несколько модификаций в вашем коде выполняют то, что вы хотите:

  • удалить все Toplevel связанные вещи в Anti_Duplicate()
  • используйте grid(...) на mainframe внутри обоих main_menu() и Anti_Duplicate()
  • добавьте main_screen.rowconfigure(0, weight=1) и main_screen.columnconfigure(0, weight=1), чтобы mainframe заполнил доступное пространство в root окне

Ниже приведено изменение main_menu() и Anti_Duplicate():

def Anti_Duplicate():
   mainframe = tk.Frame(bg='#1c2028')
   mainframe.grid(row=0, column=0, sticky='nsew') # use grid to overlay frame in same cell

   bouton_1 = HoverButton(mainframe, font=("Arial", 10), text="Back",
                          background='#1c2028', fg='white', borderwidth=2,
                          activebackground='#202124', activeforeground='#1195cf',
                          relief='ridge', command=mainframe.destroy)  # destroy mainframe
   bouton_1.place(x=520, y=300)

   open_button = HoverButton(mainframe, font=("Arial", 10), text="Ouvrir un fichier..",
                             background='#1c2028', fg='white', borderwidth=2,
                             activebackground='#202124', activeforeground='#1195cf',
                             relief='ridge', command=OpenFile1)
   open_button.place(relx=.5, y=200, anchor='n')

   bouton_2 = tk.Button(mainframe, font=("Arial", 10),
                        text="Cet outil a pour but de supprimer les lignes en double d'un fichier texte.",
                        background='#202124', fg='#1195cf', borderwidth=2,
                        activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
   bouton_2.place(relx=.5, y=50, anchor='n')

   bouton_1 = tk.Button(mainframe, font=("Arial", 15), text="Anti-Duplicate",
                        background='#202124', fg='#1195cf',  borderwidth=2,
                        activebackground='#202124', activeforeground='#1195cf', relief='sunken')
   bouton_1.pack(padx=5, pady=10, ipadx= 30)

def main_menu():
   main_screen = tk.Tk()
   main_screen.lift()
   screenn_x = int(main_screen.winfo_screenwidth())
   main_screen.config(background='#1c2028')
   screenn_y = int(main_screen.winfo_screenheight()) 
   main_screen.title("ComboKit v0.0.1")
   windowss_x = 570
   windowss_y = 340

   possX = (screenn_x // 2) - (windowss_x // 2)
   possY = (screenn_y // 2) - (windowss_y // 2)

   geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
   main_screen.geometry(geoo)

   # make frame at row=0 and column=0 to fill available space in root window    
   main_screen.rowconfigure(0, weight=1)
   main_screen.columnconfigure(0, weight=1)

   mainframe = tk.Frame(main_screen, bg='#1c2028')
   mainframe.grid(row=0, column=0, sticky='n') # use grid() instead of pack()

   bouton_1 = HoverButton(mainframe, font=("Arial", 15), text="Fusion",
                          background='#1c2028', fg='white', borderwidth=2,
                          activebackground='#202124', activeforeground='#1195cf',
                          relief='ridge', command=None)
   bouton_1.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   bouton_2 = HoverButton(mainframe, font=("Arial", 15), text="Anti-Duplicate",
                          background='#1c2028', fg='white', borderwidth=2,
                          activebackground='#202124', activeforeground='#1195cf',
                          relief='ridge', command=Anti_Duplicate)
   bouton_2.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   bouton_3 = HoverButton(mainframe, font=("Arial", 15), text="Split",
                          background='#1c2028', fg='white', borderwidth=2,
                          activebackground='#202124', activeforeground='#1195cf',
                          relief='ridge', command=None)
   bouton_3.pack(side= "left", padx= 5, pady=5, ipadx= 30)

   main_screen.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...