NameError: global name 'messagebox' is not defined - CONSOLE MODE - python

I've imported tkinter.messagebox, and my program runs smoothly when I F5 and test it on IDLE.
However my program doesn't run on console when a messagebox should be displayed, and I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\lib\tkinter\__init__.py", line 1456, in __call__
return self.func(*args)
File "U:\my documents\6th form\A2\Computing\F454\Code and Prototyping\trackeve
nts.py", line 204, in validation
messagebox.showerror("Data invalid", "The data you have entered is invalid.
Please make sure you have submitted it correctly.")
NameError: global name 'messagebox' is not defined
My importing of messagebox and the section of code if it's needed:
import tkinter.messagebox
def validation():
(...)
elif completedValidation == False:
messagebox.showerror("Data invalid", "The data you have entered is invalid. Please make sure you have submitted it correctly.")

If you import tkinter.messagebox, you have to refer to it as such: with tkinter.messagebox. If you want to alias it to just messagebox, you need from tkinter import messagebox.

try this
import Tkinter
import tkMessageBox
#rest of the code and replace the below line
tkMessageBox.showerror("Data invalid", "The data you have entered is invalid. Please make sure you have submitted it correctly.")

Related

Why does from tkinter import * not import Tkinter's messagebox?

I am learning Python, and as I try some code using tkinter I hit this issue:
I import all the definitions of tkinter with the line:
from tkinter import *
Then I try to open a message box:
messagebox.showinfo(message='My message')
But when I run the program, if this line must be executed, I get the message:
Traceback (most recent call last):
File ...
...
NameError: name 'messagebox' is not defined
If I add to the import line an explicit import for messagebox:
from tkinter import *
from tkinter import messagebox
it works, but I don't understand the reason why I have to add this import.
messagebox is a module, e.g. messagebox.py. This is not automatically imported into the namespace when you from tkinter import *. What is automatically imported is what tkinter.__init__ defines as __all__:
__all__ = [name for name, obj in globals().items()
if not name.startswith('_') and not isinstance(obj, types.ModuleType)
and name not in {'wantobjects'}]
Notice that tkinter even explicitly excludes anything that is types.ModuleType, which messagebox falls under.
When in doubt about this type of thing, you can always check out the CPython tkinter Python lib itself.
The Python docs' Importing * From a Package contain more detail.

NameError: name 'win' is not defined with tkinter python

After Executing This code i am getting error win not found running tkinter from different function is important as its a homework
Code:
import tkinter as tk
from tkinter import *
def zui(kaj,saj):
zun=kaj
kaj=kaj+"=tk.Tk()"
exec(kaj)
saj=zun+".title('"+saj+"')"
exec(saj)
def zabel(self,naj,iaj,oaj,baj,gaj,taj):
spsp=self+"="+"Label("+naj+", text='"+iaj+"', bg='"+oaj+"', height="+gaj+", width="+taj+",fg='"+baj+"')"
spsp=str(spsp)
exec(spsp)
def zosition(qak,iak,nak):
sspp=qak+".grid(row="+iak+", column="+nak+")"
exec(sspp)
def zainzoop(tak):
sft=tak+".mainloop()"
exec(sft)
zui("win","zahid app")
zabel("label","win","hello world","white","black","4","10")
zosition("win","1","1")
zainzoop("win")
Traceback:
Traceback (most recent call last):
File "c:/PyProjects/Patient Data Entry/hello.py", line 20, in <module>
zabel("label","win","hello world","white","black","4","10")
File "c:/PyProjects/Patient Data Entry/hello.py", line 12, in zabel
exec(spsp)
File "<string>", line 1, in <module>
NameError: name 'win' is not defined
This is a very weird way on using tkinter, anyway who am I to judge. exec() takes a globals() argument to make the declaration global. This is how the exec should look like:
exec(spsp,globals())
exec(sspp,globals())
exec(sft,globals())
and then in the end, zosition() should be called like:
zosition("label","1","1")
Just in case your curious on how it would normally look like:
import tkinter as tk
kaj = tk.Tk()
kaj.title('zahid app')
spsp = tk.Label(kaj,text='Hello World',bg='white',fg='black',height=4,width=10)
spsp.grid(row=1,column=1)
kaj.mainloop() #much easier right?

Combining selenium test class and tkinter

This is my first attempt at using the Tkinter plugin, I know very little past what tutorials I could find. All the answers I've seen so far put a class inside the py file that your building, I however have a plethora of tests that are already compiled into a Test class that runs many separate tests. All the tests run and no errors are encountered before trying to add to the ui.
I would like to be able to run each suite by clicking a button. My problem seems that I'm missing a step some where but not getting any errors or action when I click the button, but an error after I click and close the ui window. I should point out that importing the settings file (which contains most of the webdriver imports) does not help either. I get the same error.
Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python37\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Python37\lib\unittest\case.py", line 663, in __call__
return self.run(*args, **kwds)
File "C:\Python37\lib\unittest\case.py", line 590, in run
testMethod = getattr(self, self._testMethodName)
AttributeError: 'Test' object has no attribute 'runTest'
My ui code:
import sys, os, tkinter, TESTadmin
top = tkinter.Tk()
a = TESTadmin.Test()
B = tkinter.Button(top, text= "Test Window", command=a )
B.pack()
top.mainloop()
for clarity my main test file:
from helpers.settings import *
from pieces import adminLogin, adminLogout, docs
class Test(unittest.TestCase):
def setUp(self):
# Maximize Window (remove quotes to use)
'''sel.maximize_window()'''
self.browser = webdriver.Firefox()
self.browser.get("https://mywebsite.net")
# We instantiate and start the browser
def testCases(self):# Add Tests Below
#log in to admin side
login = adminLogin.AdminLogin.do(self)
#docs page
docpage = docs.Docs.do(self)
#log out
logout = adminLogout.Logout.do(self)
if G.log:
for k in G.log.items():
print(k)
### Uncomment to close browser after test ###
def tearDown(self):
self.browser.close()
if __name__ == "__main__":
unittest.main()
As it would turn out, the answer like I thought is simple.
this line :
def testCases(self):
needs to read:
def runTest(self):
after that change every thing works percectly.
My confusion is because originally when building these tests I was following the directions here -> https://selenium-python.readthedocs.io/
They show you to use the testCases() method, and this works! Just not for calling the class. I didn't know where to put the function let alone know that Webdriver had a built in function other than what i was using.

How to Click a Button with PyWinAuto

I am trying to do something (I think) should simple I am trying to select a button named "Start". I have been looking for documentation that describes how-to click a button (with descent example). I have been unable to find any. Anyway here is the error I get:
Traceback (most recent call last):
File "C:\Python Scripts\TestVBApp2.py", line 18, in <module>
vbButton1 = ButtonWrapper(vbapp.Button.WrapperObject("Start")).Click
TypeError: WrapperObject() takes 1 positional argument but 2 were given
Here is the code:
from pywinauto.application import Application
from time import sleep
from pywinauto.controls.win32_controls import ButtonWrapper
import pyautogui
pyautogui.FAILSAFE = True
app = Application().Start(cmd_line=u'"C:\\VBPrograms\\SimpleWPFApp.exe"')
app.MainWindow.Wait('ready')
vbapp = app.window_(title_re="MainWindow")
vbButton1 = ButtonWrapper(vbapp.Button.WrapperObject("Start")).Click
Attached is a screenshot of the app with the "Start" button.
Try to change the last line into vbapp.Start.click()

global name 'display' is not found

I'm currently designing a code for a troubleshooter. My problem is that when I press "other", there should be a data entry form label, which there is. But when i type something into it and press continue, it shows an error that says "
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File"R:\ICT\ControlledAssessment_15_17\Computing\Unit3\RiddhiSharma\FinalTroubleshooter.py", line 15, in click
display.insert(END, key)
NameError: global name 'display' is not defined
I think the problem in my actual code is here:
def click():
display.insert(END, key)
output.delete(0.0, END)
try:
entered_text=entry.get()
definition = my_glossary[entered_text]
except:
definition = "There is no entry for this word."
output.insert(END, definition)
Apparently display is not part of the tkinter module or it is not defined altogether. So when you try to use it, it raises an error because you have not defined display as a variable, function, class etc. So define display is a function that takes two arguments, END and key.
When defining display. You could do something like this:
display = 123
You could also make it a ENTRY, or whatever display is supposed to be. In your case, display doesn't have to be equal to 123. It could be equal to a class:
display = Display()
Just define Display() first... but display can be anything you want, as long you define it and use it correctly.
#PythonMaster thanks a lot for your help. To solve my problem I replaced the display function and wrote the code out like this:
def click():
entered_text = entry.get()
output.delete(0.0, END)
try:
definition = my_glossary[entered_text]
except:
definition = "There is no entry for this word."
output.insert(END, definition)

Categories