Tkinter MessageBox gives error - python

In a GUI program written in Python 3.5 I use the Tkinter module. I define a function to call the MessageBox as follows:
def callAbout():
messagebox.showinfo(title = "About", message = "My Window")
When I try to execute, I get the following error message:
Exception in Tkinter callback
Traceback (most recent call last):
[PATH]
return self.func(*args)
File "tk-error.py", line 4, in callAbout
messagebox.showinfo(title = "About", message = "My Window")
NameError: name 'messagebox' is not defined
It seems that the program cannot find
messagebox
but I wonder why, since I imported the whole module with
from tkinter import *
Please, ask if you need the complete code.
Thanks in advance for your help.
Added: Here follows the whole code.
from tkinter import *
def callAbout():
messagebox.showinfo(title = "About", message = "My Window")
win = Tk()
win.geometry('300x300')
win.title("My First Window")
bar_menu = Menu(win)
menu_about = Menu(bar_menu, tearoff = 0)
bar_menu.add_cascade(label = "About", menu = menu_about)
menu_about.add_command(label = "About", command = callAbout)
win.config(menu = bar_menu)
win.mainloop()

You can import and use the messagebox module by using an alias:
import tkinter.messagebox as tkmb
Here is your code after making changes,
import tkinter as tk
import tkinter.messagebox as tkmb
def callAbout():
tkmb.showinfo(title = "About", message = "My Window")
win = tk.Tk()
win.geometry('300x300')
win.title("My First Window")
bar_menu = tk.Menu(win)
menu_about = tk.Menu(bar_menu, tearoff = 0)
bar_menu.add_cascade(label = "About", menu = menu_about)
menu_about.add_command(label = "About", command = callAbout)
win.config(menu = bar_menu)
win.mainloop()

I had same problem.
I changed the code like this. simply...
from tkinter import *
from tkinter import messagebox

messagebox, along with some other modules like filedialog, does not automatically get imported when you import tkinter. Import it explicitly, using as and/or from as desired. check below 3 examples for better clarification-
>>> import tkinter
>>> tkinter.messagebox.showinfo(message='hi')
Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'messagebox'
.
>>> import tkinter.messagebox
>>> tkinter.messagebox.showinfo(message='hi')
'ok'
.
>>> from tkinter import messagebox
>>> messagebox.showinfo(message='hi')
'ok'

Change messagebox.showinfo to showinfo and add from tkinter.messagebox import showinfo
from tkinter import *
from tkinter.messagebox import showinfo
def callAbout():
showinfo(title="About", message="My Window")
win = Tk()
win.geometry('300x300')
win.title("My First Window")
bar_menu = Menu(win)
menu_about = Menu(bar_menu, tearoff=0)
bar_menu.add_cascade(label="About", menu=menu_about)
menu_about.add_command(label="About", command=callAbout)
win.config(menu=bar_menu)
win.mainloop()
Output:

Related

How to call another python script from a .py file in a new window

I ran into a problem where I want to click a button on a fullscreen app.
test1
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os
root = Tk()
root.title('Gamesim')
root.geometry('500x400')
def cmdopen():
os.system('C:\Users\User\Desktop\test2.py')
btn = Button(text='test', command=cmdopen)
btn.pack()
root.mainloop()
test2
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os
root = Tk()
root.title('Gamesim')
root.geometry('1870x1080')
root.attributes("-topmost", True)
btn = Button(text='test2')
btn.pack()
root.mainloop()
What it does it displays the test2 interface, but test one stops responding. What I want is that the test2 will apear above and both will respond and are diffrent windows.
Im bad in english so sorry if I have some problems.
If you're okay with having one "master" window that keeps track of the other windows, then you can do something like this:
from tkinter import *
from tkinter.ttk import *
from functools import partial
class subWindow(Toplevel):
def __init__(self, master=None):
super().__init__(master=master)
def createSubwindow(master):
"""Creates a subWindow of 'master' and sets it's options"""
subWin = subWindow(master)
subWin.title('SubWindow')
subWin.geometry('500x400')
subWin.attributes("-topmost", True)
btn = Button(subWin, text='Button Inside of SubWindow')
btn.pack()
# Creating the master-window
root = Tk()
root.title('MasterWindow')
root.geometry('500x400')
# Creates a partial of the createSubwindow, so that we can execute it easier in the button.
subWinPartial = partial(createSubwindow, root)
# Installs the button, with the partial function as a command.
btn = Button(root, text='Create Sub Window', command=subWinPartial)
btn.pack()
# Runs the mainloop, that handles all the windows.
root.mainloop()

Creating a UI for a Python Program. Theming with ttk themes for tkinter but it doesn't work for labels and buttons and returns a strange error

Here is the code written so far... The code basically functions as a UI for another Python program. The other python program isn't causing any trouble...
No one has been able to assist me with the previous post so I rephrased and reposted...
import tkinter as tk
from tkinter import ttk
from ttkthemes import themed_tk as tk
import subprocess
import sys
import time
import os
import tkinter.font as font
from tkinter.ttk import *
app = tk.ThemedTk()
app.get_themes()
app.set_theme("radiance")
app.geometry("400x400")
app.configure(bg='gray')
ex_activate_photo = tk.PhotoImage(file=r"C:\Users\bedga\PycharmProjects\GUIdev\ex_button_active.png") #It underlines PhotoImage
myFont = font.Font(family='Helvetica', size=20, weight='normal')
ttk.Label(app, text='Ex', bg='gray', font=(
'Verdana', 15)).pack(side=tk.TOP, pady=10)
app.iconbitmap(r'C:\Users\ex\ex_icon.ico')
def ex_activation():
global pro
print("Ex")
pro = subprocess.Popen("python ex.py", shell=True)
def ex_stop():
global pro
print("Stopping Program... Please Wait!")
os.kill(pro.pid, 0)
ex_activation_button = ttk.Button(app, bg='black', image=ex_activate_photo, width=120, height=120, command=ex_activation)
ex_stop_button = ttk.Button(app, bg='Gray', text='Stop Program', width=12, command=ex_stop, height=3)
ex_stop_button['font'] = myFont
app.title("Ex")
ex_activation_button.pack(side=tk.TOP)
ex_stop_button.pack(side=tk.LEFT)
# app.mainloop()
while True:
try:
app.update()
app.update_idletasks()
except KeyboardInterrupt:
pass
The goal here is to ultimately theme every button (2) and the label at the top. I can then apply similar methods when theming new things in the future. Currently, the PhotoImage is not liking tk and ttk. The program underlines it. One of the buttons being themed is photo-based and the other is text. I have seen successful projects with themed image buttons.
This is the error I get with tk.photoimage
Traceback (most recent call last):
File "C:/Users/ex/main.py", line 19, in <module>
ex_activate_photo = tk.PhotoImage(file=r"C:\Users\ex\ex_button_active.png") #It underlines PhotoImage
AttributeError: module 'ttkthemes.themed_tk' has no attribute 'PhotoImage'
EDIT: This is the error I get for doing
import tkinter as tk
from ttkthemes import themed_tk as tkk
import subprocess
import sys
import time
import os
import tkinter.font as font
from tkinter.ttk import *
I get this error:
Traceback (most recent call last):
File "C:/Users/ex/main.py", line 19, in <module>
ex_activate_photo = tk.PhotoImage(file=r"C:\Users\ex\ex_button_active.png") #It underlines PhotoImage
File "C:\Users\ex\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3539, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\ex\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3495, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\ex\PycharmProjects\ex\ex_button_active.png": no such file or directory
I didn't think ttk themes would have an issue with PhotoImage as a variable because it is a theming library for tkinter.
I am very new the GUI development in Python and any help greatly appreciated.
You are importing 2 libraries as tk, that's your main problem. First 3 lines of your code is here
import tkinter as tk
from tkinter import ttk
from ttkthemes import themed_tk as tk
First and third lines have as tk so the latest one is taking over. The error message points to this as well. You should rename one of them.

Not able to use tkinter in ArcMap

I am using Tkinter in ArcMap Add-in python code. Tkinter UI is opening well but then it closes or crashes ArcMap.
I am using the below code.
import arcpy
import pythonaddins
from Tkinter import *
import tkMessageBox
class ButtonClass1(object):
"""Implementation for Testing_addin.button (Button)"""
def __init__(self):
self.enabled = True
self.checked = False
def onClick(self):
root = Tk()
lbl = Label(root, text = "Hello")
lbl.pack()
btn = Button(root, text = "OK")
root.mainloop()
pass
Thank you!

Create directory in a selected path using Python Tkinter 2.7

I would like to create a class in Tkinter Python 2.7 that creates a new directory using the name introduced by the user in a field after the directory location was chosen from filedialog.
As an example I would like something like this:
User introduces the name of the directory and the following structure should be created:
$HOME\a\<name_introduced_by_the_user_in_the_field>\b
$HOME\a\<name_introduced_by_the_user_in_the_field>\c
I was thinking to start simple and create a simple directory, but I am getting an error.
Here is what I have tried:
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self,text="Insert the name of your project",font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
self.projectnamevar=tk.StringVar()
projectname=tk.Entry(self,textvariable=projectnamevar)
projectname.pack()
button1 = tk.Button(self, text="Create the directory", command=self.create_dir)
button1.pack()
def create_dir(self):
call(["mkdir",projectnamevar.get()])
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "program.py", line 118, in create_dir
call(["mkdir",self.projectnamevar.get()])
AttributeError: PageThree instance has no attribute 'projectnamevar'
How can I accomplish the whole stuff?
P.S. I am quite new to programming
Your Variable projectnamevar cannot be found in the class as you have not saved it as such, try it with
self.projectnamevar = tk.StringVar()
Also, you might want to use the os module instead of calling it on the system, you can use it like this
import os
path = "~/my/path/"
os.mkdir(path)
import os, sys
if sys.version_info[0] == 3:
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import *
elif sys.version_info[0] == 2:
print ("The Script is written for Python 3.6.4 might give issues with python 2.7, let the author know")
print ("Note Python 2.7 CSV has a empty line between each result. couldn't find a fix for that")
from Tkinter import *
import tkMessageBox as messagebox
import tkFileDialog as filedialog
from ttk import Combobox
class temp:
def __init__(self):
self.top = Tk()
self.lab = Label(self.top, text='UserFiled')
self.en = Entry(self.top, width =25)
self.but = Button(self.top, text='Submit',command = self.chooseFolder)
self.lab.grid(row=0, column=0)
self.en.grid(row=0, column=1)
self.but.grid(row=0, column=2)
self.top.mainloop()
def chooseFolder(self):
directory = filedialog.askdirectory()
print(directory)
newPath = os.path.join(directory, self.en.get())
if not os.path.exists(newPath):
os.chdir(directory)
os.mkdir(self.en.get())
obj = temp()

Tkinter Messagebox causing Entry to disable

So I was creating a simple input window with Tkinter but whenever i have a showinfo displaying i can't type in the entry box
import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
root = tk.Tk()
root.title("hello world")
root.minsize(700,600)
abc = StringVar()
abc.set("abc")
Entry(root, bd = 1, width = 50, textvariable=abc).pack(side = TOP)
showinfo('info', 'hello')
root.mainloop()
I'm not sure if there is something wrong with my Python (3.4) or tkinter but whenever i take out the showinfo line I can type into the Entry box but when its there i can't.
tkinter messagebox default dialog boxes are modal. What this means is that you need
to close the child window(the tkinter messagebox) before you can return to the parent application.
So, there is nothing wrong with your python or tkinter; This behavior is intended.
Don't show the tkinter messagebox before the event loop is started. Try this:
import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
def callback():
showinfo("info", "hello")
root = tk.Tk()
root.title("hello world")
root.minsize(700,600)
abc = StringVar()
abc.set("abc")
Entry(root, bd=1, width=50, textvariable=abc).pack(side=TOP)
Button(root, text="OK", command=callback).pack()
root.mainloop()
The solution i made for this is overriding the messagebox.showerror so for example i made
import logging
from tkinter import messagebox
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [%(levelname)s] %(name)s "%(message)s"',
)
LOGGER = logging.getLogger(__name__)
def test_showerror(title, message):
LOGGER.debug(f'{title} Message -> {message}')
messagebox.showerror = test_showerror
actually that's how i deal with many problems that face me during writing tests.. i override utility functions to add logging or avoid a case.

Categories

Resources