def loadTheme(self, folderpath):
print("Loading theme: {}".format(folderpath))
self.observer.unschedule_all()
if os.path.isdir(folderpath):
self.app_config['theme_folder'] = folderpath
self.loadConfig(self.text_config, os.path.join(folderpath,'textcolor.cfg'), argb_check=True)
failed_to_load = []
for key in self.i:
failed_filename = self.loadImage(folderpath, key)
if failed_filename:
failed_to_load.append("{}.png".format(failed_filename))
if failed_to_load:
failed_to_load.sort()
messagebox.showwarning("Error", 'Failed to load {}/{} image(s):\n{}'.format(len(failed_to_load), len(self.i)-3, "\n".join(failed_to_load)))
self.observer.schedule(FSEventHandler(self), folderpath, recursive=False)
else:
messagebox.showwarning("Error", 'Theme path not found:\n{}'.format(folderpath))
python类showwarning()的实例源码
def loadTheme(self, folderpath):
print("Loading theme: {}".format(folderpath))
self.observer.unschedule_all()
if os.path.isdir(folderpath):
self.app_config['theme_folder'] = folderpath
self.loadConfig(self.text_config, os.path.join(folderpath,'textcolor.cfg'), argb_check=True)
failed_to_load = []
for key in self.i:
failed_filename = self.loadImage(folderpath, key)
if failed_filename:
failed_to_load.append("{}.png".format(failed_filename))
if failed_to_load:
failed_to_load.sort()
messagebox.showwarning("Error", 'Failed to load {}/{} image(s):\n{}'.format(len(failed_to_load), len(self.i)-3, "\n".join(failed_to_load)))
self.observer.schedule(FSEventHandler(self), folderpath, recursive=False)
self.rebuildCache()
else:
messagebox.showwarning("Error", 'Theme path not found:\n{}'.format(folderpath))
def main():
# ?????????,?????Tkinter????????Tk??.??????withdraw()??????
tk = tkinter.Tk()
tk.withdraw() # ?????
print(dir(mb))
# ??,?????????,??ok,????????????.??????????????,??????????.
# ??,???Cancel?,??????None
mb.showinfo("Title", "Your message here")
mb.showerror("An Error", "Oops!")
mb.showwarning("Title", "This may not work...")
mb.askyesno("Title", "Do you love me?")
mb.askokcancel("Title", "Are you well?")
mb.askquestion("Title", "How are you?")
mb.askretrycancel("Title", "Go again?")
mb.askyesnocancel("Title", "Are you well?")
UsersInterface.py 文件源码
项目:CS-4400-Georgia-Restaurant-Inspections-report-database
作者: itsxiaoxiaoxiaoxiaoyu
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
def operatorButtonClicked(self):
username = self.username.get()
password = self.password.get()
if not username:
messagebox.showwarning("Username input is empty", "Please enter username.")
return False
if not password:
messagebox.showwarning("Password input is empty", "Please enter password")
return False
isAnOperatorUsername = self.cursor.execute("SELECT * FROM operatorowner WHERE username = %s", username)
if not isAnOperatorUsername:
messagebox.showwarning("Username is not an operator\'s username",
"The username you entered is not an operator\'s username.")
return False
usernameAndPasswordMatch = self.cursor.execute(
"SELECT * FROM registereduser WHERE (username = %s AND password = %s)", (username, password))
if not usernameAndPasswordMatch:
messagebox.showwarning("Username and password don\'t match", "Sorry, the username and password you entered"
+ " do not match.")
return False
self.loginWindow.withdraw()
operator = Operator(username)
return True
UsersInterface.py 文件源码
项目:CS-4400-Georgia-Restaurant-Inspections-report-database
作者: itsxiaoxiaoxiaoxiaoyu
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def inspectorButtonClicked(self):
username = self.username.get()
password = self.password.get()
if not username:
messagebox.showwarning("Username input is empty", "Please enter username.")
return False
if not password:
messagebox.showwarning("Password input is empty", "Please enter password")
return False
isAnInspectorUsername = self.cursor.execute("SELECT * FROM inspector WHERE username = %s", username)
if not isAnInspectorUsername:
messagebox.showwarning("Username is not an inspector\'s username",
"The username you entered is not an inspector\'s username.")
return False
usernameAndPasswordMatch = self.cursor.execute(
"SELECT * FROM registereduser WHERE (username = %s AND password = %s)", (username, password))
if not usernameAndPasswordMatch:
messagebox.showwarning("Username and password don\'t match", "Sorry, the username and password you entered"
+ " do not match.")
return False
self.loginWindow.withdraw()
inspector = Inspector()
return True
def _searchCity(self):
self.info.delete(u'1.0', tk.END)
_cityName = self.cityName.get()
if len(_cityName) == 0:
messagebox.showwarning(u'Please input a city name', u'Please input a city name for search.')
return
cities = self.api.queryCityInfo(_cityName)
# print(cities)
if len(cities) == 0:
messagebox.showerror(u'???????', u'??????????????')
return
elif len(cities) == 1:
self._showWeather(cities[0])
else:
self._askForSelect(cities)
def processMessages(self):
try:
while True:
type, args = self._queue.get_nowait()
if type == _MSG_UPDATE:
text, progress = args
self.lbl_info.config(text=text)
if self.determinate:
self.pb_progress.config(value=progress)
elif type == _MSG_CLOSE:
self.destroy()
elif type == _MSG_NOTIFY:
title, message = args
messagebox.showwarning(title, message, parent=self)
except queue.Empty:
pass
self.after(100, self.processMessages)
def check_click1(self, controller, w):
"""
This function pass the user choosed time as parameters to method combined_function1 and call the combined_function1 method.
Parameters:
w: tk.Listbox()
controller
Execptions:
catch IndexError exceptions to let user choose some stuff in the listbox
"""
try:
if (not w.curselection()):
raise IndexError
if w.get(w.curselection()) == 'Tight':
self.combined_function1(1, controller)
elif w.get(w.curselection()) == 'Moderate':
self.combined_function1(2, controller)
elif w.get(w.curselection()) == 'Adequate':
self.combined_function1(3, controller)
except IndexError:
messagebox.showwarning("Error", "Please select one of the items in the listbox")
def check_click2(self, w):
"""
This function choose the last paramter, and then call the trip_planer function to design the travel route
for users automatically including the attractions, hotels and restaurant recommendations based on their prefenrances,
and output the results in a txt file.
Parameters:
w: tk.Listbox()
Execptions:
catch IndexError exceptions to let user choose some stuff in the listbox
"""
try:
if (not w.curselection()):
raise IndexError
elif w.get(w.curselection()) == 'Tight Schedule':
t = trip_plan(Time, Bugdet, 2)
t.trip_planer()
elif w.get(w.curselection()) == 'Flexible Schedule':
t = trip_plan(Time, Bugdet, 1)
t.trip_planer()
except IndexError:
messagebox.showwarning("Error", "Please select one of the items in the listbox")
def check_click4(self, w, controller):
"""
This function let user choose what they want to overview from 'Restaurant', 'hotel', 'museum', 'attraction',
and plot their heatmap in a html file, and open it automaticlly.
Parameters:
w: tk.Listbox()
Execptions:
catch IndexError exceptions to let user choose some stuff in the listbox
"""
try:
if (not w.curselection()):
raise IndexError
if w.get(w.curselection()) == 'Restaurant':
controller.show_frame(Overview_restaurant, lat, logi)
elif w.get(w.curselection()) == 'Hotel':
controller.show_frame(Overview_hotel, lat, logi)
elif w.get(w.curselection()) == 'Attraction':
controller.show_frame(Overview_attractions, lat, logi)
elif w.get(w.curselection()) == 'Museum':
controller.show_frame(Overview_museums, lat, logi)
except IndexError:
messagebox.showwarning("Error", "Please select one of the items in the listbox")
def warningBox(self, title, message):
self.topLevel.update_idletasks()
MessageBox.showwarning(title, message)
self.__bringToFront()
def warningBox(self, title, message):
self.topLevel.update_idletasks()
MessageBox.showwarning(title, message)
self.__bringToFront()
GUI_message_box_warning.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
def _msgBox():
# msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:'
# '\nThe year is 2017.')
msg.showwarning('Python Message Warning Box', 'A Python GUI created using tkinter:'
'\nWarning: There might be a bug in this code.')
# Add another Menu to the Menu Bar and an item
GUI_message_box_error.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def _msgBox():
# msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.')
# msg.showwarning('Python Message Warning Box', 'A Python GUI created using tkinter:'
# '\nWarning: There might be a bug in this code.')
msg.showerror('Python Message Error Box', 'A Python GUI created using tkinter:'
'\nError: Houston ~ we DO have a serious PROBLEM!')
# Add another Menu to the Menu Bar and an item
def load_properties(self):
try:
with open("properties.json", "r") as file:
self.properties = json.loads(jsonesque.process(file.read()))
file.close()
except FileNotFoundError:
# print("{} | FileNotFoundError: 'properties.json' not found.".format(datetime.now().strftime("%H:%M:%S")))
messagebox.showwarning(title="Warning", message="Could not find 'properties.json'.")
def write_properties(self, key, value):
try:
with open("properties.json", "w+") as file:
self.properties[key] = value
# print(self.properties)
file.write(json.dumps(self.properties, sort_keys=False, indent=2))
file.close()
except FileNotFoundError:
# print("{} | FileNotFoundError: 'properties.json' not found.".format(datetime.now().strftime("%H:%M:%S")))
messagebox.showwarning(title="Warning", message="Could not find 'properties.json'.")
def validate(self):
try:
result = self.getresult()
except ValueError:
messagebox.showwarning(
"Illegal value",
self.errormessage + "\nPlease try again",
parent = self
)
return 0
if self.minvalue is not None and result < self.minvalue:
messagebox.showwarning(
"Too small",
"The allowed minimum value is %s. "
"Please try again." % self.minvalue,
parent = self
)
return 0
if self.maxvalue is not None and result > self.maxvalue:
messagebox.showwarning(
"Too large",
"The allowed maximum value is %s. "
"Please try again." % self.maxvalue,
parent = self
)
return 0
self.result = result
return 1
def validate(self):
try:
result = self.getresult()
except ValueError:
messagebox.showwarning(
"Illegal value",
self.errormessage + "\nPlease try again",
parent = self
)
return 0
if self.minvalue is not None and result < self.minvalue:
messagebox.showwarning(
"Too small",
"The allowed minimum value is %s. "
"Please try again." % self.minvalue,
parent = self
)
return 0
if self.maxvalue is not None and result > self.maxvalue:
messagebox.showwarning(
"Too large",
"The allowed maximum value is %s. "
"Please try again." % self.maxvalue,
parent = self
)
return 0
self.result = result
return 1
def show_warning(self, title, message):
return messagebox.showwarning(title, message)
def show_warning(self, title, message):
return messagebox.showwarning(title, message)
def validate(self):
try:
result = self.getresult()
except ValueError:
messagebox.showwarning(
"Illegal value",
self.errormessage + "\nPlease try again",
parent = self
)
return 0
if self.minvalue is not None and result < self.minvalue:
messagebox.showwarning(
"Too small",
"The allowed minimum value is %s. "
"Please try again." % self.minvalue,
parent = self
)
return 0
if self.maxvalue is not None and result > self.maxvalue:
messagebox.showwarning(
"Too large",
"The allowed maximum value is %s. "
"Please try again." % self.maxvalue,
parent = self
)
return 0
self.result = result
return 1
def hit_me():
#tk.messagebox.showinfo(title='Hi',message='hahaha')?????????????
#?????????
# msgbox.showinfo(title='Hi',message='hahaha')
#?????????
msgbox.showwarning(title='Hi',message='Fuck!')
#?????????
msgbox.showerror(title='Hi',message='ERROR!!')
#???????,????YES?NO
msgbox.askquestion(title='Hi',message='ERROR!!')
def confirm(self):
port_1 = 'https://api.47ks.com/webcloud/?v='
port_2 = 'http://www.wmxz.wang/video.php?url='
port_3 = 'http://www.vipjiexi.com/yun.php?url='
#??????????????
if re.match(r'^https?:/{2}\w.+$', self.url.get()):
#?????????????
if (self.b1.get() + self.b2.get() + self.b3.get()) !=1:
msgbox.showwarning(title='??',message='????????')
elif self.b1.get() == True:
webbrowser.open(port_1 + self.url.get())
elif self.b2.get() == True:
webbrowser.open(port_2 + self.url.get())
else:
self.b3.get() == True
webbrowser.open(port_2 + self.url.get())
else:
msgbox.showerror(title='??',message='?????????!')
def lookResult():
GlobalVal.username = GlobalVal.root.usernameInput.get()
if not os.path.exists(GlobalVal.username):
m_title = "????"
m = '??? \' %s \' ?????'% GlobalVal.username
messagebox.showwarning(m_title, m)
else:
def sub_lookResult():
subprocess.call('explorer %s' % GlobalVal.username)
t_lookResult = threading.Thread(target=sub_lookResult, name='sub_lookResult')
t_lookResult.start()
# ??????
def notify_messagebox(self, _title, _message, _kind=None):
"""Override as this is the top class, default is error."""
if self.suppress_errors is None:
if _kind == "message":
messagebox.showinfo(_title, _message)
elif _kind == "warning":
messagebox.showwarning(_title, _message)
else:
messagebox.showerror(_title, _message)
def button_load_learning_result_clicked(self):
global episode
initialdir = os.path.dirname(os.path.realpath(__file__))
while True:
if platform.system() == 'Darwin':
q_index_path = askopenfilename(initialdir=initialdir, message='Choose q_index',
filetypes=[('pickle files', '*.pickle'),
("All files", "*.*") ])
else:
q_index_path = askopenfilename(initialdir=initialdir, title='Choose q_index',
filetypes=[('pickle files', '*.pickle'),
("All files", "*.*") ])
if 'q_index' not in q_index_path:
messagebox.showwarning(message='Wrong file.')
else:
break
while True:
if platform.system() == 'Darwin':
q_table_path = askopenfilename(initialdir=initialdir, message='Choose q_table',
filetypes=[('pickle files', '*.pickle'),
("All files", "*.*") ])
else:
q_table_path = askopenfilename(initialdir=initialdir, title='Choose q_table',
filetypes=[('pickle files', '*.pickle'),
("All files", "*.*") ])
if 'q_table' not in q_table_path:
messagebox.showwarning(message='Wrong file.')
else:
break
try:
hunter.q_table = pd.read_pickle(q_table_path)
hunter.q_index = pd.read_pickle(q_index_path)
episode = [int(d) for d in q_table_path.split('_') if d.isdigit()][0]
self.label_episode_v.set('Episode: %s' % episode)
except Exception as e:
messagebox.showerror(message=e)
def loadConfig(self, config_dict, filename, argb_check=False):
print("Loading config: {}".format(filename))
if os.path.isfile(filename):
with open(filename) as f:
config_content = [line.rstrip('\n') for line in f]
malformed_color = []
for key in config_dict:
for line in config_content:
value = line.split("=")[1]
if key == line.split("=")[0]:
if argb_check:
argbstring = re.compile(r'[a-fA-F0-9]{8}$')
if argbstring.match(value):
A = value[:2]
RGB = swapRGBBGR(value[2:])
config_dict.update({key : {'rgb' : RGB, 'alpha' : A} })
else:
malformed_color.append(line)
else:
if key == "screen_gap" or key == "anim_duration":
try:
value = int(value)
except:
value = config_dict[key]
config_dict.update({key : value})
if malformed_color:
malformed_color.sort()
messagebox.showwarning("Error", "Malformed text color (ABGR):\n{}".format('\n'.join(malformed_color)))
def loadConfig(self, config_dict, filename, argb_check=False):
print("Loading config: {}".format(filename))
if os.path.isfile(filename):
with open(filename) as f:
config_content = [line.rstrip('\n') for line in f]
malformed_color = []
for key in config_dict:
for line in config_content:
value = line.split("=")[1]
if key == line.split("=")[0]:
if argb_check:
argbstring = re.compile(r'[a-fA-F0-9]{8}$')
if argbstring.match(value):
a, b, g, r = tuple([value[i:i+2] for i in range(0, len(value), 2)])
config_dict.update({key : (int(r, 16), int(g, 16), int(b, 16), int(a, 16)) })
self.sliders[key][0].set(int(a, 16))
else:
malformed_color.append(line)
else:
if key == "screen_gap" or key == "anim_duration":
try:
value = int(value)
except:
value = config_dict[key]
config_dict.update({key : value})
if malformed_color:
malformed_color.sort()
messagebox.showwarning("Error", "Malformed text color (ABGR):\n{}".format('\n'.join(malformed_color)))
def notify_messagebox(self, _title, _message, _kind=None):
"""Override as this is the top class, default is error."""
if self.suppress_errors is None:
if _kind == "message":
messagebox.showinfo(_title, _message)
elif _kind == "warning":
messagebox.showwarning(_title, _message)
else:
messagebox.showerror(_title, _message)
def DisplayError(errorMsg):
messagebox.showwarning(PROGRAM_TITLE,errorMsg)