Python Forum
[Tkinter] Top Level Window - from tkinter import *
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Top Level Window - from tkinter import *
#1
Hi guys, my main programs are based a lot of from subprocess call, but that is giving me problems (it doesn't matter why). I think i could write any code creating a new Top Level Window, but as you will see below, the main issue is from tkinter import * is not allowed. The new tkinter window code is only required that module. If i remove it, it will show only a window with a small, looks like a off button in the middle. And nothing of the remaining code. How can i make it work?

def next_version():
    Utilizador.set('')
    bot.set('')
    import tkinter as tk

    failure_max = 3
    passwords = [('alfa', 'nenebot'), ('alfa1', 'nenebot1'), ('alfa2', 'nenebot2'), ('alfa3', 'nenebot3'), ('alfa4', 'nenebot4'), ('alfa5', 'nenebot5')]

    def make_entry(parent, caption, width=None, **options):
        tk.Label(parent, text=caption).pack(side=tk.TOP)
        entry = tk.Entry(parent, **options)
        if width:
            entry.config(width=width)
        entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
        return entry

    def enter(event):
        check_password()

    def check_password():
        """ Collect 1's for every failure and quit program in case of failure_max failures """

        if (user.get(), password.get()) in passwords:
            check_password.user = user.get()
            new_winF()
        check_password.failures += 1
        if check_password.failures == failure_max:
            root.destroy()
            raise SystemExit('Acesso Recusado')
        else:
            root.title('Tente novamente.')
    check_password.failures = 0

    root = tk.Tk()
    root_height = 160
    root_width = 300
    root.title('Login Obrigatório')
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x_cordinate = int((screen_width/2) - (root_width/2))
    y_cordinate = int((screen_height/2) - (root_height/2))
    root.geometry("{}x{}+{}+{}".format(root_width, root_height, x_cordinate, y_cordinate))

    user = make_entry(root, "Utilizador:", 16, show='')
    password = make_entry(root, "Password:", 16, show="*")

    b = tk.Button(root, borderwidth=4, text="Login", width=10, pady=8, command=check_password)
    b.pack(side=tk.BOTTOM)
    password.bind('<Return>', enter)

    user.focus_set()
    root.resizable(False,False)
    root.mainloop()
   
def new_winF():
    from tkinter import *

    root = Tk()
    root_height = 202
    root_width = 456
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x_cordinate = int((screen_width/2) - (root_width/2))
    y_cordinate = int((screen_height/2) - (root_height/2))
    root.geometry("{}x{}+{}+{}".format(root_width, root_height, x_cordinate, y_cordinate))

    var = StringVar()
    label = Label( root, textvariable=var, relief=RAISED )

    var.set("""     NeneBot v1.1 Beta
    ---------------------------------------------------------------------------------------------
    1º reparação de todos os bugs reportados
    *********************************************************************************************
    2º melhorias na estrutura da App
    *********************************************************************************************
    3º melhoria na App em termos de facilidade de leitura
    *********************************************************************************************
    4º adição de calculadora de IP
    *********************************************************************************************
    5º organizador de ficheiros (um clique e todos os ficheiros em pasta)
    *********************************************************************************************
    6º adição de outras funcionalidades mediante sugestões reportadas""")

    label.pack()
    root.resizable(False,False)
    root.mainloop()

Attached Files

Thumbnail(s)
   
Reply
#2
bold, italic and underline inside python code tags doesn't work, also i can't quite follow what you are asking Confused .
Reply
#3
(Apr-23-2019, 07:34 PM)Yoriz Wrote: bold, italic and underline inside python code tags doesn't work, also i can't quite follow what you are asking Confused .
You can open a new tkinter window based on the main code, don't know if you saw the picture, the code requires from tkinter import *, but it gives an error if i apply it saying: import * only allowed at module level
Reply
#4
import tkinter as tk is the preferred way of importing, see https://python-forum.io/Thread-Namespace...th-imports
you should only need one root.mainloop()
The error is because you are trying to use from tkinter import * inside a function
Imports should go at the start of your python file.

It looks like you have put two separate windows codes together in a way which they shouldn't be.
Reply
#5
I got it to work, the new window opens, but kills the main program. If you saw my post first picture the window wasn't showing nothing at all. Now on this one is showing my text (fine so far). You will understand better by this picture attached below

Resuming:
- the user will insert a password, if correct the new tkinter window, will open to display the text
- then the user should be able to return to the main program, right now it isn't happening, for some reason the main program goes blank.
- for example on the step the user input a password, that window can be closed and the person will return to the main program, on this next one it doesn't

def new_winF():
    t = Toplevel(root)
    import tkinter as tk
    
    root_height = 202
    root_width = 456
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x_cordinate = int((screen_width/2) - (root_width/2))
    y_cordinate = int((screen_height/2) - (root_height/2))
    root.geometry("{}x{}+{}+{}".format(root_width, root_height, x_cordinate, y_cordinate))

    var = StringVar()
    label = Label( root, textvariable=var, relief=RAISED )

    var.set("""     NeneBot v1.1 Beta
    ---------------------------------------------------------------------------------------------
    1º reparação de todos os bugs reportados
    *********************************************************************************************
    2º melhorias na estrutura da App
    *********************************************************************************************
    3º melhoria na App em termos de facilidade de leitura
    *********************************************************************************************
    4º adição de calculadora de IP
    *********************************************************************************************
    5º organizador de ficheiros (um clique e todos os ficheiros em pasta)
    *********************************************************************************************
    6º adição de outras funcionalidades mediante sugestões reportadas""")

    label.pack()

Attached Files

Thumbnail(s)
   
Reply
#6
I'm not great with tkinter but i think your code should be more along the lines of the following.
I don't totally understand tkinters tk.TK(), in WxPython you create a wx.App() but they don't quite seem to be the same thing,
so i may have some of the root stuff mixed up, someone who knows tkinter may be able to tidy that up, but it works.
import tkinter as tk

class NextVersionFrame(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.root = root

# def next_version():
#     Utilizador.set('')
#     bot.set('')
#     import tkinter as tk
        self.failures = 0
        self.failure_max = 3
        self.passwords = [('alfa', 'nenebot'), ('alfa1', 'nenebot1'),
                 ('alfa2', 'nenebot2'), ('alfa3', 'nenebot3'),
                 ('alfa4', 'nenebot4'), ('alfa5', 'nenebot5')]



        root_height = 160
        root_width = 300
        self.root.title('Login Obrigat�rio')
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x_cordinate = int((screen_width/2) - (root_width/2))
        y_cordinate = int((screen_height/2) - (root_height/2))
        self.root.geometry("{}x{}+{}+{}".format(
            root_width, root_height, x_cordinate, y_cordinate))

        self.user = self.make_entry("Utilizador:", 16, show='')
        self.password = self.make_entry("Password:", 16, show="*")

        b = tk.Button(
            self, borderwidth=4, text="Login", width=10, pady=8,
            command=self.check_password)
        b.pack(side=tk.BOTTOM)
        self.password.bind('<Return>', self.enter)

        self.user.focus_set()
        self.root.resizable(False,False)
        self.pack()

    def make_entry(self, caption, width=None, **options):
        tk.Label(self, text=caption).pack(side=tk.TOP)
        entry = tk.Entry(self, **options)
        if width:
            entry.config(width=width)
        entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
        return entry

    def enter(self, event):
        self.check_password()

    def check_password(self):
        """ Collect 1's for every failure and quit program in case of failure_max failures """
        

        if (self.user.get(), self.password.get()) in self.passwords:
            self.user = self.user.get()
            NewWinFrame(self)
        self.failures += 1
        if self.failures == self.failure_max:
            self.destroy()
            raise SystemExit('Acesso Recusado')
        else:
            root.title('Tente novamente.')
        

class NewWinFrame(tk.Toplevel):
    def __init__(self, parent):
        super(NewWinFrame, self).__init__(parent)

# def new_winF():
#     from tkinter import *
 
#     root = Tk()
        root_height = 202
        root_width = 456
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x_cordinate = int((screen_width/2) - (root_width/2))
        y_cordinate = int((screen_height/2) - (root_height/2))
        self.geometry("{}x{}+{}+{}".format(root_width, root_height, x_cordinate, y_cordinate))
     
        var = tk.StringVar()
        label = tk.Label( self, textvariable=var, relief=tk.RAISED )
     
        var.set("""     NeneBot v1.1 Beta
        ---------------------------------------------------------------------------------------------
        1� repara��o de todos os bugs reportados
        *********************************************************************************************
        2� melhorias na estrutura da App
        *********************************************************************************************
        3� melhoria na App em termos de facilidade de leitura
        *********************************************************************************************
        4� adi��o de calculadora de IP
        *********************************************************************************************
        5� organizador de ficheiros (um clique e todos os ficheiros em pasta)
        *********************************************************************************************
        6� adi��o de outras funcionalidades mediante sugest�es reportadas""")
     
        label.pack()
        self.resizable(False,False)


if __name__ == '__main__':
    root = tk.Tk()
    next_version_frame = NextVersionFrame(root)
    root.mainloop()
Reply
#7
(Apr-23-2019, 09:18 PM)Yoriz Wrote: I'm not great with tkinter but i think your code should be more along the lines of the following. I don't totally understand tkinters tk.TK(), in WxPython you create a wx.App() but they don't quite seem to be the same thing, so i may have some of the root stuff mixed up, someone who knows tkinter may be able to tidy that up, but it works.
import tkinter as tk class NextVersionFrame(tk.Frame): def __init__(self, root): super().__init__(root) self.root = root # def next_version(): # Utilizador.set('') # bot.set('') # import tkinter as tk self.failures = 0 self.failure_max = 3 self.passwords = [('alfa', 'nenebot'), ('alfa1', 'nenebot1'), ('alfa2', 'nenebot2'), ('alfa3', 'nenebot3'), ('alfa4', 'nenebot4'), ('alfa5', 'nenebot5')] root_height = 160 root_width = 300 self.root.title('Login Obrigat�rio') screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() x_cordinate = int((screen_width/2) - (root_width/2)) y_cordinate = int((screen_height/2) - (root_height/2)) self.root.geometry("{}x{}+{}+{}".format( root_width, root_height, x_cordinate, y_cordinate)) self.user = self.make_entry("Utilizador:", 16, show='') self.password = self.make_entry("Password:", 16, show="*") b = tk.Button( self, borderwidth=4, text="Login", width=10, pady=8, command=self.check_password) b.pack(side=tk.BOTTOM) self.password.bind('<Return>', self.enter) self.user.focus_set() self.root.resizable(False,False) self.pack() def make_entry(self, caption, width=None, **options): tk.Label(self, text=caption).pack(side=tk.TOP) entry = tk.Entry(self, **options) if width: entry.config(width=width) entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH) return entry def enter(self, event): self.check_password() def check_password(self): """ Collect 1's for every failure and quit program in case of failure_max failures """ if (self.user.get(), self.password.get()) in self.passwords: self.user = self.user.get() NewWinFrame(self) self.failures += 1 if self.failures == self.failure_max: self.destroy() raise SystemExit('Acesso Recusado') else: root.title('Tente novamente.') class NewWinFrame(tk.Toplevel): def __init__(self, parent): super(NewWinFrame, self).__init__(parent) # def new_winF(): # from tkinter import * # root = Tk() root_height = 202 root_width = 456 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() x_cordinate = int((screen_width/2) - (root_width/2)) y_cordinate = int((screen_height/2) - (root_height/2)) self.geometry("{}x{}+{}+{}".format(root_width, root_height, x_cordinate, y_cordinate)) var = tk.StringVar() label = tk.Label( self, textvariable=var, relief=tk.RAISED ) var.set(""" NeneBot v1.1 Beta --------------------------------------------------------------------------------------------- 1� repara��o de todos os bugs reportados ********************************************************************************************* 2� melhorias na estrutura da App ********************************************************************************************* 3� melhoria na App em termos de facilidade de leitura ********************************************************************************************* 4� adi��o de calculadora de IP ********************************************************************************************* 5� organizador de ficheiros (um clique e todos os ficheiros em pasta) ********************************************************************************************* 6� adi��o de outras funcionalidades mediante sugest�es reportadas""") label.pack() self.resizable(False,False) if __name__ == '__main__': root = tk.Tk() next_version_frame = NextVersionFrame(root) root.mainloop()

Much appreciated, i will try and test it right away.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Tkinter Window Has no Title Bar gw1500se 4 304 Nov-07-2021, 05:14 PM
Last Post: gw1500se
  "tkinter.TclError: NULL main window" Rama02 1 1,720 Feb-04-2021, 06:45 PM
Last Post: deanhystad
  function in new window (tkinter) Dale22 7 1,310 Nov-24-2020, 11:28 PM
Last Post: Dale22
  Scrollable big image in a window (TKinter) Prospekteur 3 1,218 Sep-14-2020, 03:06 AM
Last Post: Larz60+
  Run more than one window together with tkinter SmukasPlays 1 776 Aug-24-2020, 05:00 PM
Last Post: Larz60+
  Adding an image to a tkinter window djwilson0495 2 3,776 Aug-23-2020, 11:07 AM
Last Post: ebolisa
  [Tkinter] calling a new window from a tkinter window neuroprogrammer 2 1,097 Jul-28-2020, 10:59 PM
Last Post: deanhystad
  How to display results from terminal window onto tkinter. buttercup 0 1,197 Jul-21-2020, 04:41 AM
Last Post: buttercup
  Tkinter: multitab window WizardMitMagi 3 1,216 Apr-29-2020, 02:40 PM
Last Post: deanhystad
  tkinter.TclError: bad window path name kenwatts275 3 5,612 Apr-26-2020, 08:16 PM
Last Post: kenwatts275

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020