Repository: TomSchimansky/GuitarTuner Branch: master Commit: 882a2f0d193d Files: 28 Total size: 112.9 KB Directory structure: gitextract_ri22e36j/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── assets/ │ ├── images/ │ │ └── GuitarTuner_Icon.icns │ └── user_settings/ │ └── user_settings.json ├── documentation/ │ ├── test_custom_button.py │ ├── test_custom_button_images.py │ ├── test_custom_button_simple.py │ └── tkinter_custom_button.py ├── main.py ├── requirements.txt ├── settings.py ├── setup.py ├── tuner_appearance_manager/ │ ├── color_manager.py │ ├── font_manager.py │ ├── image_manager.py │ └── timing.py ├── tuner_audio/ │ ├── __init__.py │ ├── audio_analyzer.py │ ├── sound_thread.py │ └── threading_helper.py ├── tuner_ui_parts/ │ ├── __init__.py │ ├── main_frame.py │ ├── settings_frame.py │ ├── tkinter_custom_button.py │ └── tkinter_custom_button_imageset.py └── usage_monitoring/ ├── __init__.py └── usage_monitor.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pyc .DS_Store /tests/ /product/ /.eggs/ /build/ /dist/ ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ ![GitHub release (latest by date)](https://img.shields.io/github/v/release/TomSchimansky/GuitarTuner) ![GitHub all releases](https://img.shields.io/github/downloads/TomSchimansky/GuitarTuner/total?color=green&label=macOS%20release%20downloads) ![GitHub Release Date](https://img.shields.io/github/release-date/TomSchimansky/GuitarTuner?color=green) # GuitarTuner App ![](documentation/readme_images/Preview_Dark.png) This is a simple **chromatic tuner** designed for guitar tuning, but it should also work with every other instrument. The played note is automatically recognized through the microphone, and an acoustic signal is heard when the tuning is correct. If you want you can also change the reference-tone to another frequency. At the moment, a compiled version is only available for macOS, but you can use it on Windows too if you run it in the command line. * Automatic tone detection * High accuracy: < 0.5 cents (around the A4 area) * Working from 60 to 2000 Hz (C2 to C7) * High stability of the pitch indicator * Support for macOS light and dark-mode ### **➜️ Download macOS app (Intel only):** [Download here](https://github.com/TomSchimansky/GuitarTuner/releases/tag/3.2) ![](documentation/readme_images/Icon_Banner.png) ### Functionality The app is written in Python with Tkinter, PyAudio and numpy. It uses PyAudio to get access to the raw audio-stream coming from the microphone. Then a **fast-fourier-transformation** (```numpy.fft```) is applied on the audio-data, which is buffered for about 1.5 seconds. Then a HPS (Harmonic Product Spectrum) operation is applied to filter the harmonic frequencies. From the HPS output, you can get the loudest frequency and convert it to a musical note by applying the following formula: ```12 * numpy.log2(f / a4_frequency) + 69```. ### Run GuitarTuner with python First you need to install all necessary libraries: ``` pip3 install -r requirements.txt ``` Then you can do: ``` python3 main.py ``` ### Create standalone application You can also create a standalone application for macOS or Windows by yourself. For macOS you can use py2app: ``` python3.8 setup.py py2app ``` For windows, you would need to use py2exe instead and modify the setup.py file. To keep application size as small as possible, make sure you create a virtual environment where you install only the necessary libraries. The macOS dark-mode currently **only** works with the **anaconda python** Version. If you compile the app with a python.org version, you have to disable the dark-mode by deleting the ```'NSRequiresAquaSystemAppearance': False```entry in setup.py, which causes the application window to go into dark-mode. ![](documentation/readme_images/Preview_Light.png) ================================================ FILE: assets/user_settings/user_settings.json ================================================ {"check_for_updates": true, "bell_muted": false, "agreed_on_usage_stats": true, "open_times": 0, "id": null} ================================================ FILE: documentation/test_custom_button.py ================================================ """ This is a small program to demonstrate the use of the TkinterCustomButton class, which is used in this project """ import tkinter import tkinter.messagebox import os import sys from distutils.version import StrictVersion as Version from tkinter_custom_button import TkinterCustomButton MAIN_PATH = os.path.dirname(__file__) APP_NAME = "Rounded Tkinter custom button test" ABOUT_TEXT = "Simple Test-App" WIDTH = 600 HEIGHT = 400 class App(tkinter.Tk): def __init__(self, *args, **kwargs): if sys.platform == "darwin": # macOS if Version(tkinter.Tcl().call("info", "patchlevel")) >= Version("8.6.9"): # Tcl/Tk >= 8.6.9 os.system("defaults write -g NSRequiresAquaSystemAppearance -bool No") # turn on dark mode for all apps # Currently this works only with anaconda python version (python.org Tcl/Tk version is only 8.6.8). tkinter.Tk.__init__(self, *args, **kwargs) self.minsize(WIDTH, HEIGHT) self.resizable(True, True) self.title(APP_NAME) self.geometry(str(WIDTH) + "x" + str(HEIGHT)) self.protocol("WM_DELETE_WINDOW", self.on_closing) self.bind("", self.on_closing) self.bind("", self.on_closing) if sys.platform == "darwin": # macOS self.menubar = tkinter.Menu(master=self) self.app_menu = tkinter.Menu(self.menubar, name='apple') self.menubar.add_cascade(menu=self.app_menu) self.app_menu.add_command(label='About ' + APP_NAME, command=self.about_dialog) self.app_menu.add_separator() self.config(menu=self.menubar) self.createcommand('tk::mac::Quit', self.on_closing) # ========== slightly rounded corners ============= self.button_1 = TkinterCustomButton(master=self, bg_color=None, fg_color="#2874A6", hover_color="#5499C7", text_font=None, text="Test Button 1", text_color="white", corner_radius=10, width=120, height=45, hover=True, command=self.test_function) self.button_1.place(relx=0.33, rely=0.2, anchor=tkinter.CENTER) self.button_2 = TkinterCustomButton(master=self, bg_color=None, fg_color="#922B21", border_color="white", hover_color="#CD6155", text_font=None, text="Test Button 2", text_color="white", corner_radius=10, border_width=2, width=150, height=45, hover=True, command=self.test_function) self.button_2.place(relx=0.66, rely=0.2, anchor=tkinter.CENTER) # ========== fully rounded corners ============= self.button_3 = TkinterCustomButton(master=self, bg_color=None, fg_color="#1E8449", hover_color="#2ECC71", text_font=None, text="Test Button 3", text_color="white", corner_radius=20, width=120, height=40, hover=True, command=self.test_function) self.button_3.place(relx=0.33, rely=0.4, anchor=tkinter.CENTER) self.button_4 = TkinterCustomButton(master=self, bg_color=None, border_color="#BB8FCE", fg_color="#6C3483", hover_color="#A569BD", text_font=None, text="Test Button 4", text_color="white", corner_radius=20, border_width=2, width=150, height=40, hover=True, command=self.test_function) self.button_4.place(relx=0.66, rely=0.4, anchor=tkinter.CENTER) # ========== no rounded corners ============= self.button_5 = TkinterCustomButton(master=self, bg_color=None, fg_color="#A93226", hover_color="#CD6155", text_font=None, text="Test Button 5", text_color="black", corner_radius=0, width=120, height=40, hover=True, command=self.test_function) self.button_5.place(relx=0.33, rely=0.6, anchor=tkinter.CENTER) self.button_6 = TkinterCustomButton(master=self, bg_color=None, fg_color=self.cget("bg"), border_color="#ABB2B9", hover_color="#566573", text_font=None, text="Test Button 6", text_color="#ABB2B9", corner_radius=0, border_width=2, width=120, height=40, hover=True, command=self.test_function) self.button_6.place(relx=0.66, rely=0.6, anchor=tkinter.CENTER) # ========== other shapes ============= from PIL import Image, ImageTk play_image = ImageTk.PhotoImage(Image.open("button_test_images/play_button_image.png").resize((30, 30))) self.button_7 = TkinterCustomButton(master=self, bg_color=None, fg_color="#58636F", border_color=None, hover_color="#808B96", image=play_image, # <- add image (class PhotoImage) corner_radius=10, border_width=0, width=50, height=50, hover=True, command=self.test_function) self.button_7.place(relx=0.33, rely=0.8, anchor=tkinter.CENTER) self.button_8 = TkinterCustomButton(master=self, bg_color=None, fg_color="#212F3D", border_color="#117A65", hover_color="#34495E", text_font=None, text="Button 8", text_color="white", corner_radius=12, border_width=4, width=100, height=60, hover=True, command=self.test_function) self.button_8.place(relx=0.66, rely=0.8, anchor=tkinter.CENTER) self.running = False def test_function(self): tkinter.messagebox.showwarning(title="Button Test", message="Button pressed") def about_dialog(self): tkinter.messagebox.showinfo(title=APP_NAME, message=ABOUT_TEXT) def on_closing(self, event=0): if sys.platform == "darwin": # macOS if Version(tkinter.Tcl().call("info", "patchlevel")) >= Version("8.6.9"): # Tcl/Tk >= 8.6.9 os.system("defaults delete -g NSRequiresAquaSystemAppearance") # turn off dark mode for all apps self.destroy() self.running = False exit() def start(self): self.running = True self.mainloop() if __name__ == "__main__": app = App() app.start() ================================================ FILE: documentation/test_custom_button_images.py ================================================ import tkinter from tkinter_custom_button import TkinterCustomButton from PIL import Image, ImageTk app = tkinter.Tk() app.geometry("300x200") app.title("TkinterCustomButton") def button_function(): print("Button pressed") play_image = ImageTk.PhotoImage(Image.open("button_test_images/play_button_image.png").resize((40, 40))) skip_image = ImageTk.PhotoImage(Image.open("button_test_images/skip_button_image.png").resize((40, 40))) button_1 = TkinterCustomButton(image=play_image, width=60, height=60, corner_radius=12, command=button_function) button_1.place(relx=0.33, rely=0.5, anchor=tkinter.CENTER) button_2 = TkinterCustomButton(image=skip_image, width=60, height=60, corner_radius=12, command=button_function) button_2.place(relx=0.66, rely=0.5, anchor=tkinter.CENTER) app.mainloop() ================================================ FILE: documentation/test_custom_button_simple.py ================================================ import tkinter from tkinter_custom_button import TkinterCustomButton app = tkinter.Tk() app.geometry("300x200") app.title("TkinterCustomButton") def button_function(): print("Button pressed") button_1 = TkinterCustomButton(text="My Button", corner_radius=10, command=button_function) button_1.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) app.mainloop() ================================================ FILE: documentation/tkinter_custom_button.py ================================================ import tkinter import sys class TkinterCustomButton(tkinter.Frame): """ tkinter custom button with border, rounded corners and hover effect Arguments: master= where to place button bg_color= background color, None is standard, fg_color= foreground color, blue is standard, hover_color= foreground color, lightblue is standard, border_color= foreground color, None is standard, border_width= border thickness, 0 is standard, command= callback function, None is standard, width= width of button, 110 is standard, height= width of button, 35 is standard, corner_radius= corner radius, 10 is standard, text_font= (, ), text_color= text color, white is standard, text= text of button, hover= hover effect, True is standard, image= PIL.PhotoImage, standard is None""" def __init__(self, bg_color=None, fg_color="#2874A6", hover_color="#5499C7", border_color=None, border_width=0, command=None, width=120, height=40, corner_radius=10, text_font=None, text_color="white", text="CustomButton", hover=True, image=None, *args, **kwargs): super().__init__(*args, **kwargs) if bg_color is None: self.bg_color = self.master.cget("bg") else: self.bg_color = bg_color self.fg_color = fg_color self.hover_color = hover_color self.border_color = border_color self.width = width self.height = height if corner_radius*2 > self.height: self.corner_radius = self.height/2 elif corner_radius*2 > self.width: self.corner_radius = self.width/2 else: self.corner_radius = corner_radius self.border_width = border_width if self.corner_radius >= self.border_width: self.inner_corner_radius = self.corner_radius - self.border_width else: self.inner_corner_radius = 0 self.text = text self.text_color = text_color if text_font is None: if sys.platform == "darwin": # macOS self.text_font = ("Avenir", 13) elif "win" in sys.platform: # Windows self.text_font = ("Century Gothic", 11) else: self.text_font = ("TkDefaultFont") else: self.text_font = text_font self.image = image self.function = command self.hover = hover self.configure(width=self.width, height=self.height) if sys.platform == "darwin" and self.function is not None: self.configure(cursor="pointinghand") self.canvas = tkinter.Canvas(master=self, highlightthicknes=0, background=self.bg_color, width=self.width, height=self.height) self.canvas.place(x=0, y=0) if self.hover is True: self.canvas.bind("", self.on_enter) self.canvas.bind("", self.on_leave) self.canvas.bind("", self.clicked) self.canvas.bind("", self.clicked) self.canvas_fg_parts = [] self.canvas_border_parts = [] self.text_part = None self.text_label = None self.image_label = None self.draw() def draw(self): self.canvas.delete("all") self.canvas_fg_parts = [] self.canvas_border_parts = [] self.canvas.configure(bg=self.bg_color) # border button parts if self.border_width > 0: if self.corner_radius > 0: self.canvas_border_parts.append(self.canvas.create_oval(0, 0, self.corner_radius * 2, self.corner_radius * 2)) self.canvas_border_parts.append(self.canvas.create_oval(self.width - self.corner_radius * 2, 0, self.width, self.corner_radius * 2)) self.canvas_border_parts.append(self.canvas.create_oval(0, self.height - self.corner_radius * 2, self.corner_radius * 2, self.height)) self.canvas_border_parts.append(self.canvas.create_oval(self.width - self.corner_radius * 2, self.height - self.corner_radius * 2, self.width, self.height)) self.canvas_border_parts.append(self.canvas.create_rectangle(0, self.corner_radius, self.width, self.height - self.corner_radius)) self.canvas_border_parts.append(self.canvas.create_rectangle(self.corner_radius, 0, self.width - self.corner_radius, self.height)) # inner button parts if self.corner_radius > 0: self.canvas_fg_parts.append(self.canvas.create_oval(self.border_width, self.border_width, self.border_width + self.inner_corner_radius * 2, self.border_width + self.inner_corner_radius * 2)) self.canvas_fg_parts.append(self.canvas.create_oval(self.width - self.border_width - self.inner_corner_radius * 2, self.border_width, self.width - self.border_width, self.border_width + self.inner_corner_radius * 2)) self.canvas_fg_parts.append(self.canvas.create_oval(self.border_width, self.height - self.border_width - self.inner_corner_radius * 2, self.border_width + self.inner_corner_radius * 2, self.height-self.border_width)) self.canvas_fg_parts.append(self.canvas.create_oval(self.width - self.border_width - self.inner_corner_radius * 2, self.height - self.border_width - self.inner_corner_radius * 2, self.width - self.border_width, self.height - self.border_width)) self.canvas_fg_parts.append(self.canvas.create_rectangle(self.border_width + self.inner_corner_radius, self.border_width, self.width - self.border_width - self.inner_corner_radius, self.height - self.border_width)) self.canvas_fg_parts.append(self.canvas.create_rectangle(self.border_width, self.border_width + self.inner_corner_radius, self.width - self.border_width, self.height - self.inner_corner_radius - self.border_width)) for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.fg_color, width=0) for part in self.canvas_border_parts: self.canvas.itemconfig(part, fill=self.border_color, width=0) # no image given if self.image is None: # create tkinter.Label with text self.text_label = tkinter.Label(master=self, text=self.text, font=self.text_font, bg=self.fg_color, fg=self.text_color) self.text_label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # bind events the the button click and hover events also to the text_label if self.hover is True: self.text_label.bind("", self.on_enter) self.text_label.bind("", self.on_leave) self.text_label.bind("", self.clicked) self.text_label.bind("", self.clicked) self.set_text(self.text) # use the given image else: # create tkinter.Label with image on it self.image_label = tkinter.Label(master=self, image=self.image, bg=self.fg_color) self.image_label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # bind events the the button click and hover events also to the image_label if self.hover is True: self.image_label.bind("", self.on_enter) self.image_label.bind("", self.on_leave) self.image_label.bind("", self.clicked) self.image_label.bind("", self.clicked) def configure_color(self, bg_color=None, fg_color=None, hover_color=None, text_color=None): if bg_color is not None: self.bg_color = bg_color else: self.bg_color = self.master.cget("bg") if fg_color is not None: self.fg_color = fg_color # change background color of image_label if self.image is not None: self.image_label.configure(bg=self.fg_color) if hover_color is not None: self.hover_color = hover_color if text_color is not None: self.text_color = text_color if self.text_part is not None: self.canvas.itemconfig(self.text_part, fill=self.text_color) self.draw() def set_text(self, text): if self.text_label is not None: self.text_label.configure(text=text) def on_enter(self, event=0): for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.hover_color, width=0) if self.text_label is not None: # change background color of image_label self.text_label.configure(bg=self.hover_color) if self.image_label is not None: # change background color of image_label self.image_label.configure(bg=self.hover_color) def on_leave(self, event=0): for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.fg_color, width=0) if self.text_label is not None: # change background color of image_label self.text_label.configure(bg=self.fg_color) if self.image_label is not None: # change background color of image_label self.image_label.configure(bg=self.fg_color) def clicked(self, event=0): if self.function is not None: self.function() self.on_leave() ================================================ FILE: main.py ================================================ import tkinter import tkinter.messagebox import os import sys import json import requests import webbrowser import time import numpy as np import random from distutils.version import StrictVersion as Version from tuner_audio.audio_analyzer import AudioAnalyzer from tuner_audio.threading_helper import ProtectedList from tuner_audio.sound_thread import SoundThread from tuner_appearance_manager.color_manager import ColorManager from tuner_appearance_manager.image_manager import ImageManager from tuner_appearance_manager.font_manager import FontManager from tuner_appearance_manager.timing import Timer from tuner_ui_parts.main_frame import MainFrame from tuner_ui_parts.settings_frame import SettingsFrame try: from usage_monitoring import usage_monitor except ImportError: """ Usage monitoring not possible, because the module is missing (Github Version is missing the module because of private API key) """ usage_monitor = None from settings import Settings class App(tkinter.Tk): def __init__(self, *args, **kwargs): if not Settings.COMPILED_APP_MODE: if sys.platform == "darwin": # macOS if Version(tkinter.Tcl().call("info", "patchlevel")) >= Version("8.6.9"): # Tcl/Tk >= 8.6.9 os.system("defaults write -g NSRequiresAquaSystemAppearance -bool No") # Only for dark-mode testing! # WARNING: This command applies macOS dark-mode on all programs. This can cause bugs on some programs. # Currently this works only with anaconda python version (python.org Tcl/Tk version is only 8.6.8). pass tkinter.Tk.__init__(self, *args, **kwargs) self.main_path = os.path.dirname(os.path.abspath(__file__)) self.color_manager = ColorManager() self.font_manager = FontManager() self.image_manager = ImageManager(self.main_path) self.frequency_queue = ProtectedList() self.main_frame = MainFrame(self) self.settings_frame = SettingsFrame(self) self.audio_analyzer = AudioAnalyzer(self.frequency_queue) self.audio_analyzer.start() self.play_sound_thread = SoundThread(self.main_path + "/assets/sounds/drop.wav") self.play_sound_thread.start() self.timer = Timer(Settings.FPS) self.needle_buffer_array = np.zeros(Settings.NEEDLE_BUFFER_LENGTH) self.tone_hit_counter = 0 self.note_number_counter = 0 self.nearest_note_number_buffered = 69 self.a4_frequency = 440 self.dark_mode_active = False self.title(Settings.APP_NAME) self.geometry(str(Settings.WIDTH) + "x" + str(Settings.HEIGHT)) self.resizable(True, True) self.minsize(Settings.WIDTH, Settings.HEIGHT) self.maxsize(Settings.MAX_WIDTH, Settings.MAX_HEIGHT) self.configure(background=self.color_manager.background_layer_1) self.protocol("WM_DELETE_WINDOW", self.on_closing) if sys.platform == "darwin": # macOS self.bind("", self.on_closing) self.bind("", self.on_closing) self.createcommand('tk::mac::Quit', self.on_closing) self.createcommand('tk::mac::ShowPreferences', self.draw_settings_frame) menu_bar = tkinter.Menu(master=self) app_menu = tkinter.Menu(menu_bar, name='apple') menu_bar.add_cascade(menu=app_menu) app_menu.add_command(label='About ' + Settings.APP_NAME, command=self.about_dialog) app_menu.add_separator() self.config(menu=menu_bar) elif "win" in sys.platform: # Windows self.bind("", self.on_closing) self.draw_main_frame() if self.read_user_setting("bell_muted") is True: self.main_frame.button_mute.set_pressed(True) self.open_app_time = time.time() @staticmethod def about_dialog(): tkinter.messagebox.showinfo(title=Settings.APP_NAME, message=Settings.ABOUT_TEXT) def draw_settings_frame(self, event=0): self.main_frame.place_forget() self.settings_frame.place(relx=0, rely=0, relheight=1, relwidth=1) def draw_main_frame(self, event=0): self.settings_frame.place_forget() self.main_frame.place(relx=0, rely=0, relheight=1, relwidth=1) def manage_usage_stats(self, open_times, id): if Settings.COMPILED_APP_MODE: # check usage_monitor module could be loaded if usage_monitor is not None: # check if user agreed on usage statistics if self.read_user_setting("agreed_on_usage_stats") is True: # send log message with option and open_times data usage_monitor.UsageMonitor.new_log_msg(open_times, id) else: # open dialog to ask for usage statistics permission answer = tkinter.messagebox.askyesno(title=Settings.APP_NAME, message=Settings.STATISTICS_AGREEMENT) if answer is True: # save user permission self.write_user_setting("agreed_on_usage_stats", True) # send log message with option and open_times data usage_monitor.UsageMonitor.new_log_msg(open_times, id) else: # close program if user doesnt agree self.on_closing() def check_for_updates(self): # check if user agreed on update checking if self.read_user_setting("check_for_updates") is True: try: # use github API to get latest version string response = requests.get(Settings.GITHUB_API_URL + "/releases/latest") latest_version = response.json()["tag_name"] except Exception as err: sys.stderr.write(str(err) + "/n") return if Version(latest_version) > Version(Settings.VERSION): answer = tkinter.messagebox.askyesno(title=Settings.APP_NAME, message="A new version of this app is available. \n\n" + "Do you want to download it?") if answer is True: webbrowser.open(Settings.GITHUB_URL + "/releases/latest") else: answer = tkinter.messagebox.askyesno(title=Settings.APP_NAME, message="Ask again next time? \n\n") if answer is False: self.write_user_setting("check_for_updates", False) def write_user_setting(self, setting, value): with open(self.main_path + Settings.USER_SETTINGS_PATH, "r") as file: user_settings = json.load(file) user_settings[setting] = value with open(self.main_path + Settings.USER_SETTINGS_PATH, "w") as file: json.dump(user_settings, file) def read_user_setting(self, setting): with open(self.main_path + Settings.USER_SETTINGS_PATH) as file: user_settings = json.load(file) return user_settings[setting] def on_closing(self, event=0): self.write_user_setting("bell_muted", self.main_frame.button_mute.is_pressed()) self.check_for_updates() if not Settings.COMPILED_APP_MODE: if sys.platform == "darwin": # macOS if Version(tkinter.Tcl().call("info", "patchlevel")) >= Version("8.6.9"): # Tcl/Tk >= 8.6.9 os.system("defaults delete -g NSRequiresAquaSystemAppearance") # Only for dark-mode testing! # This command reverts the dark-mode setting for all programs. pass self.audio_analyzer.running = False self.play_sound_thread.running = False self.destroy() def update_color(self): self.main_frame.update_color() self.settings_frame.update_color() def handle_appearance_mode_change(self): dark_mode_state = self.color_manager.detect_os_dark_mode() if dark_mode_state is not self.dark_mode_active: if dark_mode_state is True: self.color_manager.set_mode("Dark") else: self.color_manager.set_mode("Light") self.dark_mode_active = dark_mode_state self.update_color() def start(self): self.handle_appearance_mode_change() # handle new usage statistics when program is started if self.read_user_setting("id") is None: self.write_user_setting("id", random.randint(10**20, (10**21)-1)) # generate random id self.write_user_setting("open_times", self.read_user_setting("open_times")+1) # increase open_times counter self.manage_usage_stats(self.read_user_setting("open_times"), self.read_user_setting("id")) # send open_times value and id while self.audio_analyzer.running: try: # handle the change from dark to light mode, light to dark mode self.handle_appearance_mode_change() # get the current frequency from the queue freq = self.frequency_queue.get() if freq is not None: # convert frequency to note number number = self.audio_analyzer.frequency_to_number(freq, self.a4_frequency) # calculate nearest note number, name and frequency nearest_note_number = round(number) nearest_note_freq = self.audio_analyzer.number_to_frequency(nearest_note_number, self.a4_frequency) # calculate frequency difference from freq to nearest note freq_difference = nearest_note_freq - freq # calculate the frequency difference to the next note (-1) semitone_step = nearest_note_freq - self.audio_analyzer.number_to_frequency(round(number-1), self.a4_frequency) # calculate the angle of the display needle needle_angle = -90 * ((freq_difference / semitone_step) * 2) # buffer the current nearest note number change if nearest_note_number != self.nearest_note_number_buffered: self.note_number_counter += 1 if self.note_number_counter >= Settings.HITS_TILL_NOTE_NUMBER_UPDATE: self.nearest_note_number_buffered = nearest_note_number self.note_number_counter = 0 # if needle in range +-5 degrees then make it green, otherwise red if abs(freq_difference) < 0.25: self.main_frame.set_needle_color("green") self.tone_hit_counter += 1 else: self.main_frame.set_needle_color("red") self.tone_hit_counter = 0 # after 7 hits of the right note in a row play the sound if self.tone_hit_counter > 7: self.tone_hit_counter = 0 if self.main_frame.button_mute.is_pressed() is not True: self.play_sound_thread.play_sound() # update needle buffer array self.needle_buffer_array[:-1] = self.needle_buffer_array[1:] self.needle_buffer_array[-1:] = needle_angle # update ui note labels and display needle self.main_frame.set_needle_angle(np.average(self.needle_buffer_array)) self.main_frame.set_note_names(note_name=self.audio_analyzer.number_to_note_name(self.nearest_note_number_buffered), note_name_lower=self.audio_analyzer.number_to_note_name(self.nearest_note_number_buffered - 1), note_name_higher=self.audio_analyzer.number_to_note_name(self.nearest_note_number_buffered + 1)) # calculate difference in cents if semitone_step == 0: diff_cents = 0 else: diff_cents = (freq_difference / semitone_step) * 100 freq_label_text = f"+{round(-diff_cents, 1)} cents" if -diff_cents > 0 else f"{round(-diff_cents, 1)} cents" self.main_frame.set_frequency_difference(freq_label_text) # set current frequency if freq is not None: self.main_frame.set_frequency(freq) self.update() self.timer.wait() except IOError as err: sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(err).__name__, err)) self.update() self.timer.wait() if __name__ == "__main__": app = App() app.start() ================================================ FILE: requirements.txt ================================================ numpy~=1.22.1 setuptools~=52.0.0 PyAudio~=0.2.11 py2app~=0.21 Pillow~=9.0.0 darkdetect~=0.1.1 requests~=2.25.1 ================================================ FILE: settings.py ================================================ class Settings: """ GuitarTuner global app configuration """ COMPILED_APP_MODE = False """ general settings """ APP_NAME = "GuitarTuner" VERSION = "3.2" AUTHOR = "Tom Schimansky" YEAR = "2021" GITHUB_API_URL = "https://api.github.com/repos/TomSchimansky/GuitarTuner" GITHUB_URL = "https://github.com/TomSchimansky/GuitarTuner" GITHUB_URL_README = "https://github.com/TomSchimansky/GuitarTuner#readme" STATISTICS_AGREEMENT = f"{APP_NAME} tracks how often the app is being opened.\n\n" + \ "Do you agree on sending this anonymous data?" USER_SETTINGS_PATH = "/assets/user_settings/user_settings.json" ABOUT_TEXT = "{} Version {} © {} {}".format(APP_NAME, VERSION, YEAR, AUTHOR) CF_BUNDLE_IDENTIFIER = "com.{}.{}".format(AUTHOR, APP_NAME) WIDTH = 450 # window size when starting the app HEIGHT = 440 MAX_WIDTH = 600 # max window size MAX_HEIGHT = 500 FPS = 60 # canvas update rate CANVAS_SIZE = 300 # size of the audio-display NEEDLE_BUFFER_LENGTH = 30 HITS_TILL_NOTE_NUMBER_UPDATE = 15 ================================================ FILE: setup.py ================================================ """ this setup.py file is build for compilation on macOS with py2app""" import os import getpass from setuptools import setup from settings import Settings REMOVE_OLD_BUILD = True # delete /build and /dist APP = ['main.py'] USER_NAME = getpass.getuser() SOUND_FILES = ["assets/sounds/drop.wav"] DATA_FILES = ["assets/user_settings/user_settings.json"] IMAGE_FILES = ["assets/images/arrowDown_hovered.png", "assets/images/arrowDown.png", "assets/images/arrowUp_hovered.png", "assets/images/arrowUp.png", "assets/images/bell_hovered.png", "assets/images/bell.png", "assets/images/mutedBell_hovered.png", "assets/images/mutedBell.png"] OPTIONS = {'argv_emulation': False, 'includes': 'numpy, tkinter, PIL, pyaudio, darkdetect, requests', 'excludes': '', 'frameworks': '/Users/{}/miniconda3/lib/libffi.6.dylib,'.format(USER_NAME) + '/Users/{}/miniconda3/lib/libtk8.6.dylib,'.format(USER_NAME) + '/Users/{}/miniconda3/lib/libtcl8.6.dylib'.format(USER_NAME), # For whatever reason, py2app didn't include these 3 frameworks automatically. (path can be different) 'iconfile': 'assets/images/GuitarTuner_Icon.icns', 'plist': { 'CFBundleName': Settings.APP_NAME, 'CFBundleDisplayName': Settings.APP_NAME, 'CFBundleExecutable': Settings.APP_NAME, 'CFBundleGetInfoString': "Tune your instrument with {}".format(Settings.APP_NAME), 'CFBundleIdentifier': Settings.CF_BUNDLE_IDENTIFIER, 'CFBundleVersion': Settings.VERSION, 'CFBundleShortVersionString': Settings.VERSION, 'NSRequiresAquaSystemAppearance': False, 'NSHumanReadableCopyright': u"Copyright {}, {}, All Rights Reserved".format(Settings.YEAR, Settings.AUTHOR) }} if REMOVE_OLD_BUILD is True: os.system("rm -r build") os.system("rm -r dist") setup(name=Settings.APP_NAME, app=APP, author=Settings.AUTHOR, data_files=[("assets/images", IMAGE_FILES), ("assets/sounds", SOUND_FILES), ("assets/user_settings", DATA_FILES)], options={'py2app': OPTIONS}, setup_requires=['py2app']) ================================================ FILE: tuner_appearance_manager/color_manager.py ================================================ import darkdetect import sys class ColorManager(object): def __init__(self): self.set_mode("Light") def set_mode(self, mode): if mode == "Dark": self.background_layer_1 = self.rgb_to_hex((50, 50, 50)) self.background_layer_0 = self.rgb_to_hex((33, 33, 33)) self.text_main = self.rgb_to_hex((255, 255, 255)) self.text_2 = self.rgb_to_hex((169, 169, 169)) self.text_2_highlight = self.rgb_to_hex((240, 240, 240)) self.theme_main = self.rgb_to_hex((51, 94, 145)) self.theme_dark = self.rgb_to_hex((26, 51, 82)) self.theme_light = self.rgb_to_hex((85, 140, 200)) self.needle = self.rgb_to_hex((107, 42, 28)) self.needle_hit = self.rgb_to_hex((43, 113, 53)) elif mode == "Light": self.background_layer_1 = self.rgb_to_hex((241, 239, 238)) self.background_layer_0 = self.rgb_to_hex((209, 208, 206)) self.text_main = self.rgb_to_hex((0, 0, 0)) self.text_2 = self.rgb_to_hex((36, 36, 36)) self.text_2_highlight = self.rgb_to_hex((0, 0, 0)) self.theme_main = self.rgb_to_hex((83, 147, 213)) self.theme_dark = self.rgb_to_hex((51, 94, 145)) self.theme_light = self.rgb_to_hex((128, 175, 223)) self.needle = self.rgb_to_hex((107, 42, 28)) self.needle_hit = self.rgb_to_hex((43, 113, 53)) @staticmethod def rgb_to_hex(rgb): return "#%02x%02x%02x" % rgb @staticmethod def detect_os_dark_mode(): if sys.platform == "darwin": if darkdetect.theme() == "Dark": return True else: return False else: return True ================================================ FILE: tuner_appearance_manager/font_manager.py ================================================ import sys class FontManager(object): """ font sizes need to be different on operating systems because on windows the text is displayed much larger """ def __init__(self): if sys.platform == "darwin": # macOS self.button_font = ("Avenir", 16) self.note_display_font = ("Avenir", 72) # main note Text self.note_display_font_medium = ("Avenir", 26) # text on left and right site self.frequency_text_font = ("Avenir", 15) self.info_text_font = ("Avenir", 14) self.settings_text_font = ("Avenir", 24) elif "win" in sys.platform: # Windows self.button_font = ("Century Gothic", 14) self.note_display_font = ("Century Gothic", 62) self.note_display_font_medium = ("Century Gothic", 24) # text on left and right site self.frequency_text_font = ("Century Gothic", 13) self.info_text_font = ("Century Gothic", 12) self.settings_text_font = ("Century Gothic", 20) else: # Linux or other self.button_font = ("Century Gothic", 14) self.note_display_font = ("Century Gothic", 62) self.note_display_font_medium = ("Century Gothic", 24) # text on left and right site self.frequency_text_font = ("Century Gothic", 13) self.info_text_font = ("Century Gothic", 12) self.settings_text_font = ("Century Gothic", 20) ================================================ FILE: tuner_appearance_manager/image_manager.py ================================================ try: import Image except ImportError: from PIL import Image try: import ImageTk except ImportError: from PIL import ImageTk class ImageManager(object): def __init__(self, main_path): self.bell_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/bell.png").resize((50, 50), Image.ANTIALIAS)) self.bell_hovered_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/bell_hovered.png").resize((50, 50), Image.ANTIALIAS)) self.bell_muted_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/mutedBell.png").resize((50, 50), Image.ANTIALIAS)) self.bell_muted_hovered_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/mutedBell_hovered.png").resize((50, 50), Image.ANTIALIAS)) self.arrowUp_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/arrowUp.png").resize((147, 46), Image.ANTIALIAS)) self.arrowUp_image_hovered = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/arrowUp_hovered.png").resize((147, 46), Image.ANTIALIAS)) self.arrowDown_image = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/arrowDown.png").resize((147, 46), Image.ANTIALIAS)) self.arrowDown_image_hovered = ImageTk.PhotoImage( Image.open(main_path + "/assets/images/arrowDown_hovered.png").resize((147, 46), Image.ANTIALIAS)) ================================================ FILE: tuner_appearance_manager/timing.py ================================================ import time import sys class Timer(object): """ Timer makes current thread sleep until time of set FPS is over. If time is already over the Timer does nothing or prints a warning if specified """ def __init__(self, fps, warnings=False): self.fps = fps self.wait_time = 1/self.fps self.last_time = time.time() self.warnings = warnings def wait(self): spend_time = time.time() - self.last_time sleep_time = self.wait_time - spend_time if sleep_time < 0: if self.warnings: sys.stderr.write("Warning: Timer delay of {} secs\n".format(round(-sleep_time, 4))) else: time.sleep(sleep_time) self.last_time = time.time() ================================================ FILE: tuner_audio/__init__.py ================================================ ================================================ FILE: tuner_audio/audio_analyzer.py ================================================ import copy from pyaudio import PyAudio, paInt16 from threading import Thread import numpy as np import sys class AudioAnalyzer(Thread): """ This AudioAnalyzer reads the microphone and finds the frequency of the loudest tone. To use it, you also need the ProtectedList class from the file threading_helper.py. You need to created an instance of the ProtectedList, which acts as a queue, and you have to pass this queue to the AudioAnalyzer. Then you can read the values from the queue: queue = ProtectedList() analyzer = AudioAnalyzer(queue) analyzer.start() while True: freq = queue.get() print("loudest frequency:", q_data, "nearest note:", a.frequency_to_note_name(q_data, 440)) time.sleep(0.02) """ # settings: (are tuned for best detecting string instruments like guitar) SAMPLING_RATE = 48000 # mac hardware: 44100, 48000, 96000 CHUNK_SIZE = 1024 # number of samples BUFFER_TIMES = 50 # buffer length = CHUNK_SIZE * BUFFER_TIMES ZERO_PADDING = 3 # times the buffer length NUM_HPS = 3 # Harmonic Product Spectrum # overall frequency accuracy (step-size): SAMPLING_RATE / (CHUNK_SIZE * BUFFER_TIMES * (1 + ZERO_PADDING)) Hz # buffer length in seconds: (CHUNK_SIZE * BUFFER_TIMES) / SAMPLING_RATE sec NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] def __init__(self, queue, *args, **kwargs): Thread.__init__(self, *args, **kwargs) self.queue = queue # queue should be instance of ProtectedList (threading_helper.ProtectedList) self.buffer = np.zeros(self.CHUNK_SIZE * self.BUFFER_TIMES) self.hanning_window = np.hanning(len(self.buffer)) self.running = False try: self.audio_object = PyAudio() self.stream = self.audio_object.open(format=paInt16, channels=1, rate=self.SAMPLING_RATE, input=True, output=False, frames_per_buffer=self.CHUNK_SIZE) except Exception as e: sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(e).__name__, e)) return @staticmethod def frequency_to_number(freq, a4_freq): """ converts a frequency to a note number (for example: A4 is 69)""" if freq == 0: sys.stderr.write("Error: No frequency data. Program has potentially no access to microphone\n") return 0 return 12 * np.log2(freq / a4_freq) + 69 @staticmethod def number_to_frequency(number, a4_freq): """ converts a note number (A4 is 69) back to a frequency """ return a4_freq * 2.0**((number - 69) / 12.0) @staticmethod def number_to_note_name(number): """ converts a note number to a note name (for example: 69 returns 'A', 70 returns 'A#', ... ) """ return AudioAnalyzer.NOTE_NAMES[int(round(number) % 12)] @staticmethod def frequency_to_note_name(frequency, a4_freq): """ converts frequency to note name (for example: 440 returns 'A') """ number = AudioAnalyzer.frequency_to_number(frequency, a4_freq) note_name = AudioAnalyzer.number_to_note_name(number) return note_name def run(self): """ Main function where the microphone buffer gets read and the fourier transformation gets applied """ self.running = True while self.running: try: # read microphone data data = self.stream.read(self.CHUNK_SIZE, exception_on_overflow=False) data = np.frombuffer(data, dtype=np.int16) # append data to audio buffer self.buffer[:-self.CHUNK_SIZE] = self.buffer[self.CHUNK_SIZE:] self.buffer[-self.CHUNK_SIZE:] = data # apply the fourier transformation on the whole buffer (with zero-padding + hanning window) magnitude_data = abs(np.fft.fft(np.pad(self.buffer * self.hanning_window, (0, len(self.buffer) * self.ZERO_PADDING), "constant"))) # only use the first half of the fft output data magnitude_data = magnitude_data[:int(len(magnitude_data) / 2)] # HPS: multiply data by itself with different scalings (Harmonic Product Spectrum) magnitude_data_orig = copy.deepcopy(magnitude_data) for i in range(2, self.NUM_HPS+1, 1): hps_len = int(np.ceil(len(magnitude_data) / i)) magnitude_data[:hps_len] *= magnitude_data_orig[::i] # multiply every i element # get the corresponding frequency array frequencies = np.fft.fftfreq(int((len(magnitude_data) * 2) / 1), 1. / self.SAMPLING_RATE) # set magnitude of all frequencies below 60Hz to zero for i, freq in enumerate(frequencies): if freq > 60: magnitude_data[:i - 1] = 0 break # put the frequency of the loudest tone into the queue self.queue.put(round(frequencies[np.argmax(magnitude_data)], 2)) except Exception as e: sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(e).__name__, e)) self.stream.stop_stream() self.stream.close() self.audio_object.terminate() if __name__ == "__main__": # Only for testing: from tuner_audio.threading_helper import ProtectedList import time q = ProtectedList() a = AudioAnalyzer(q) a.start() while True: q_data = q.get() if q_data is not None: print("loudest frequency:", q_data, "nearest note:", a.frequency_to_note_name(q_data, 440)) time.sleep(0.02) ================================================ FILE: tuner_audio/sound_thread.py ================================================ from threading import Thread import pyaudio import wave import time class SoundThread(Thread): """ Simple threaded class that takes a path to an audio.wav file and the plays it when SoundThread.play_sound() is called. """ def __init__(self, path_to_file): Thread.__init__(self) self.running = False self.data_chunk_size = 1024 self.audio_file = wave.open(path_to_file, "rb") self.audio_file_data = [] # load audio file into audio_file_data while True: data = self.audio_file.readframes(self.data_chunk_size) if data != b'': self.audio_file_data.append(data) else: break self.py_audio_object = pyaudio.PyAudio() audio_format = self.py_audio_object.get_format_from_width(self.audio_file.getsampwidth()) self.audio_stream = self.py_audio_object.open(format=audio_format, channels=self.audio_file.getnchannels(), rate=self.audio_file.getframerate(), input=False, output=True) self.play_sound_now = False self.audio_file.close() def play_sound(self): self.play_sound_now = True def run(self): self.running = True while self.running: if self.play_sound_now is True: for audio_chunk in self.audio_file_data: self.audio_stream.write(audio_chunk) self.play_sound_now = False time.sleep(1) else: time.sleep(0.1) self.audio_stream.stop_stream() self.audio_stream.close() self.py_audio_object.terminate() ================================================ FILE: tuner_audio/threading_helper.py ================================================ from threading import Lock class ProtectedList(object): """ Simple queue to share data between Threads with lock protection. Standard buffer length is only 8! """ def __init__(self, buffer_size=8): self.elements = [] self.buffer_size = buffer_size self.lock = Lock() def put(self, element): self.lock.acquire() # append new element at the end of the list self.elements.append(element) # delete oldest element if list is too long if len(self.elements) > self.buffer_size: self.elements.pop(0) self.lock.release() def get(self): self.lock.acquire() # check if something is in the list if len(self.elements) > 0: element = self.elements[0] del self.elements[0] # if list is empty return None else: element = None self.lock.release() return element def __repr__(self): self.lock.acquire() string = str(self.elements) self.lock.release() return string ================================================ FILE: tuner_ui_parts/__init__.py ================================================ ================================================ FILE: tuner_ui_parts/main_frame.py ================================================ import tkinter from math import sin, radians from tuner_ui_parts.tkinter_custom_button_imageset import TkinterCustomButtonImageset from tuner_ui_parts.tkinter_custom_button import TkinterCustomButton from settings import Settings class MainFrame(tkinter.Frame): def __init__(self, master, *args, **kwargs): tkinter.Frame.__init__(self, master, *args, **kwargs) self.app_pointer = master self.color_manager = self.app_pointer.color_manager self.font_manager = self.app_pointer.font_manager self.image_manager = self.app_pointer.image_manager self.configure(bg=self.color_manager.background_layer_1) self.under_canvas = tkinter.Canvas(master=self, bg=self.color_manager.background_layer_1, highlightthickness=0, height=Settings.CANVAS_SIZE, width=Settings.CANVAS_SIZE) self.under_canvas.place(anchor=tkinter.CENTER, relx=0.5, rely=0.5) self.display_outer_circle = self.under_canvas.create_oval(0, 0, Settings.CANVAS_SIZE - 1, Settings.CANVAS_SIZE - 1, fill=self.color_manager.theme_main, width=0) self.display_background_line = self.under_canvas.create_line(Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5, -Settings.CANVAS_SIZE * 0.5, fill=self.color_manager.background_layer_1, width=Settings.CANVAS_SIZE * 0.05) self.needle_width = 8 self.display_needle = self.under_canvas.create_line(Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.05, fill=self.color_manager.needle, width=self.needle_width, capstyle=tkinter.ROUND) self.display_inner_circle_1 = self.under_canvas.create_oval(Settings.CANVAS_SIZE * 0.2, Settings.CANVAS_SIZE * 0.2, Settings.CANVAS_SIZE * 0.8, Settings.CANVAS_SIZE * 0.8, fill=self.color_manager.theme_dark, width=0) self.botton_frame = tkinter.Frame(master=self, bg=self.color_manager.background_layer_0) self.botton_frame.place(relx=0, rely=0.5, relheight=0.5, relwidth=1) self.upper_canvas = tkinter.Canvas(master=self.botton_frame, bg=self.color_manager.background_layer_0, highlightthickness=0, height=Settings.CANVAS_SIZE / 2, width=Settings.CANVAS_SIZE) self.upper_canvas.place(anchor=tkinter.N, relx=0.5, rely=0) self.display_inner_circle_2 = self.upper_canvas.create_oval(Settings.CANVAS_SIZE * 0.2, -Settings.CANVAS_SIZE * 0.3, Settings.CANVAS_SIZE * 0.8, Settings.CANVAS_SIZE * 0.3, fill=self.color_manager.theme_dark, width=0) self.note_label = tkinter.Label(master=self, text="A", bg=self.color_manager.theme_dark, fg=self.color_manager.text_2, font=self.font_manager.note_display_font) self.note_label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) self.higher_note_text = self.upper_canvas.create_text(Settings.CANVAS_SIZE * 0.95, Settings.CANVAS_SIZE * 0.1, anchor=tkinter.E, text="A#", fill=self.color_manager.text_2, font=self.font_manager.note_display_font_medium) self.lower_note_text = self.upper_canvas.create_text(Settings.CANVAS_SIZE * 0.05, Settings.CANVAS_SIZE * 0.1, anchor=tkinter.W, text="B#", fill=self.color_manager.text_2, font=self.font_manager.note_display_font_medium) self.frequency_text = self.upper_canvas.create_text(Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.16, anchor=tkinter.N, text="- Hz", fill=self.color_manager.text_2, font=self.font_manager.frequency_text_font) self.button_frequency = TkinterCustomButton(master=self.botton_frame, bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_font=self.font_manager.button_font, text="440 Hz", text_color=self.color_manager.text_main, corner_radius=10, width=110, height=40, hover=False, command=None) self.button_frequency.place(anchor=tkinter.SW, relx=0.05, rely=0.9) self.button_info = TkinterCustomButton(master=self.botton_frame, bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_font=self.font_manager.button_font, text="Info", text_color=self.color_manager.text_main, corner_radius=10, width=110, height=40, command=self.master.draw_settings_frame) self.button_info.place(anchor=tkinter.SE, relx=0.95, rely=0.9) self.button_mute = TkinterCustomButtonImageset(master=self, bg_color=self.color_manager.background_layer_1, image_dict={"standard": self.image_manager.bell_image, "clicked": self.image_manager.bell_muted_image, "standard_hover": self.image_manager.bell_hovered_image, "clicked_hover": self.image_manager.bell_muted_hovered_image}, height=self.image_manager.bell_image.height(), width=self.image_manager.bell_image.width()) self.button_mute.place(anchor=tkinter.NE, relx=0.95, rely=0.05) def update_color(self): self.configure(bg=self.color_manager.background_layer_1) self.under_canvas.configure(bg=self.color_manager.background_layer_1) self.under_canvas.itemconfig(self.display_background_line, fill=self.color_manager.background_layer_1) self.under_canvas.itemconfig(self.display_outer_circle, fill=self.color_manager.theme_main) self.under_canvas.itemconfig(self.display_inner_circle_1, fill=self.color_manager.theme_dark) self.upper_canvas.configure(bg=self.color_manager.background_layer_0) self.upper_canvas.itemconfig(self.display_inner_circle_2, fill=self.color_manager.theme_dark) self.note_label.configure(bg=self.color_manager.theme_dark, fg=self.color_manager.text_2) self.upper_canvas.itemconfig(self.higher_note_text, fill=self.color_manager.text_2) self.upper_canvas.itemconfig(self.lower_note_text, fill=self.color_manager.text_2) self.upper_canvas.itemconfig(self.frequency_text, fill=self.color_manager.text_2) self.button_mute.label.configure(bg=self.color_manager.background_layer_1) self.botton_frame.configure(bg=self.color_manager.background_layer_0) self.button_frequency.configure_color(bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_color=self.color_manager.text_main) self.button_info.configure_color(bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_color=self.color_manager.text_main) def set_needle_color(self, color): if color == "green": self.under_canvas.itemconfig(self.display_needle, fill=self.color_manager.needle_hit) self.note_label.configure(fg=self.color_manager.text_2_highlight, font=self.font_manager.note_display_font) elif color == "red": self.under_canvas.itemconfig(self.display_needle, fill=self.color_manager.needle) self.note_label.configure(fg=self.color_manager.text_2, font=self.font_manager.note_display_font) def set_needle_angle(self, deg): x = sin(radians(180 - deg)) y = sin(radians(270 - deg)) self.under_canvas.coords(self.display_needle, Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5, Settings.CANVAS_SIZE * 0.5 + (Settings.CANVAS_SIZE * 0.45 * x), Settings.CANVAS_SIZE * 0.5 + (Settings.CANVAS_SIZE * 0.45 * y)) return x, y def set_note_names(self, note_name, note_name_lower, note_name_higher): self.note_label.configure(text=note_name, width=3) self.upper_canvas.itemconfig(self.higher_note_text, text=note_name_higher) self.upper_canvas.itemconfig(self.lower_note_text, text=note_name_lower) def set_frequency(self, frequency): self.upper_canvas.itemconfig(self.frequency_text, text=str(round(frequency, 1)) + " Hz") def set_frequency_difference(self, frequency): self.button_frequency.set_text(str(frequency)) ================================================ FILE: tuner_ui_parts/settings_frame.py ================================================ import tkinter import webbrowser from tuner_ui_parts.tkinter_custom_button_imageset import TkinterCustomButtonImageset from tuner_ui_parts.tkinter_custom_button import TkinterCustomButton from settings import Settings class SettingsFrame(tkinter.Frame): def __init__(self, master, *args, **kwargs): tkinter.Frame.__init__(self, master, *args, **kwargs) self.app_pointer = master self.color_manager = self.app_pointer.color_manager self.font_manager = self.app_pointer.font_manager self.image_manager = self.app_pointer.image_manager self.configure(bg=self.color_manager.background_layer_1) self.bottom_frame = tkinter.Frame(master=self, bg=self.color_manager.background_layer_0) self.bottom_frame.place(anchor=tkinter.S, relx=0.5, rely=1, relheight=0.2, relwidth=1) self.button_back = TkinterCustomButton(master=self.bottom_frame, bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_font=self.font_manager.button_font, text="Back", text_color=self.color_manager.text_main, corner_radius=10, width=110, height=40, command=self.master.draw_main_frame) self.button_back.place(anchor=tkinter.SE, relx=0.95, rely=0.75) self.button_website = TkinterCustomButton(master=self.bottom_frame, bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_font=self.font_manager.button_font, text="Website", text_color=self.color_manager.text_main, corner_radius=10, width=110, height=40, command=self.website_button) self.button_website.place(anchor=tkinter.SW, relx=0.05, rely=0.75) self.label_info_text = tkinter.Label(master=self, bg=self.color_manager.background_layer_1, fg=self.color_manager.text_2, font=self.font_manager.info_text_font, text=Settings.ABOUT_TEXT) self.label_info_text.place(anchor=tkinter.CENTER, relx=0.5, rely=0.12, relheight=0.2, relwidth=0.8) self.label_note_text = tkinter.Label(master=self, bg=self.color_manager.background_layer_1, fg=self.color_manager.text_2, font=self.font_manager.settings_text_font, text="A4 =") self.label_note_text.place(relx=0.2, rely=0.45, relheight=0.1, relwidth=0.2, anchor=tkinter.CENTER) self.label_frequency = TkinterCustomButton(master=self, bg_color=self.color_manager.background_layer_1, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_main, text_font=self.font_manager.settings_text_font, text="440 Hz", text_color=self.color_manager.text_main, corner_radius=10, width=170, height=65, hover=False) self.label_frequency.place(anchor=tkinter.CENTER, relx=0.5, rely=0.45) self.button_frequency_up = TkinterCustomButtonImageset(master=self, height=50, width=150, bg_color=self.color_manager.background_layer_1, image_dict={"standard": self.image_manager.arrowUp_image, "clicked": self.image_manager.arrowUp_image, "standard_hover": self.image_manager.arrowUp_image_hovered, "clicked_hover": self.image_manager.arrowUp_image_hovered}, command=self.frequency_button_up) self.button_frequency_up.place(anchor=tkinter.CENTER, relx=0.5, rely=0.3) self.button_frequency_down = TkinterCustomButtonImageset(master=self, height=50, width=150, bg_color=self.color_manager.background_layer_1, image_dict={"standard": self.image_manager.arrowDown_image, "clicked": self.image_manager.arrowDown_image, "standard_hover": self.image_manager.arrowDown_image_hovered, "clicked_hover": self.image_manager.arrowDown_image_hovered}, command=self.frequency_button_down) self.button_frequency_down.place(anchor=tkinter.CENTER, relx=0.5, rely=0.6) def update_color(self): self.configure(bg=self.color_manager.background_layer_1) self.bottom_frame.configure(bg=self.color_manager.background_layer_0) self.button_back.configure_color(bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_color=self.color_manager.text_main) self.button_website.configure_color(bg_color=self.color_manager.background_layer_0, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_color=self.color_manager.text_main) self.label_info_text.configure(bg=self.color_manager.background_layer_1, fg=self.color_manager.text_2) self.label_note_text.configure(bg=self.color_manager.background_layer_1, fg=self.color_manager.text_2) self.label_frequency.configure_color(bg_color=self.color_manager.background_layer_1, fg_color=self.color_manager.theme_main, hover_color=self.color_manager.theme_light, text_color=self.color_manager.text_main) self.button_frequency_up.label.configure(bg=self.color_manager.background_layer_1) self.button_frequency_down.label.configure(bg=self.color_manager.background_layer_1) def frequency_button_up(self): self.master.a4_frequency += 1 self.label_frequency.set_text(str(self.master.a4_frequency) + " Hz") def frequency_button_down(self): if self.master.a4_frequency > 1: self.master.a4_frequency -= 1 self.label_frequency.set_text(str(self.master.a4_frequency) + " Hz") def website_button(self): webbrowser.open(Settings.GITHUB_URL_README) ================================================ FILE: tuner_ui_parts/tkinter_custom_button.py ================================================ import tkinter import sys class TkinterCustomButton(tkinter.Frame): """ tkinter custom button with border, rounded corners and hover effect Arguments: master= where to place button bg_color= background color, None is standard, fg_color= foreground color, blue is standard, hover_color= foreground color, lightblue is standard, border_color= foreground color, None is standard, border_width= border thickness, 0 is standard, command= callback function, None is standard, width= width of button, 110 is standard, height= width of button, 35 is standard, corner_radius= corner radius, 10 is standard, text_font= (, ), text_color= text color, white is standard, text= text of button, hover= hover effect, True is standard, image= PIL.PhotoImage, standard is None""" def __init__(self, bg_color=None, fg_color="#2874A6", hover_color="#5499C7", border_color=None, border_width=0, command=None, width=120, height=40, corner_radius=10, text_font=None, text_color="white", text="CustomButton", hover=True, image=None, *args, **kwargs): super().__init__(*args, **kwargs) if bg_color is None: self.bg_color = self.master.cget("bg") else: self.bg_color = bg_color self.fg_color = fg_color self.hover_color = hover_color self.border_color = border_color self.width = width self.height = height if corner_radius * 2 > self.height: self.corner_radius = self.height / 2 elif corner_radius * 2 > self.width: self.corner_radius = self.width / 2 else: self.corner_radius = corner_radius self.border_width = border_width if self.corner_radius >= self.border_width: self.inner_corner_radius = self.corner_radius - self.border_width else: self.inner_corner_radius = 0 self.text = text self.text_color = text_color if text_font is None: if sys.platform == "darwin": # macOS self.text_font = ("Avenir", 13) elif "win" in sys.platform: # Windows self.text_font = ("Century Gothic", 11) else: self.text_font = ("TkDefaultFont") else: self.text_font = text_font self.image = image self.function = command self.hover = hover self.configure(width=self.width, height=self.height) if sys.platform == "darwin" and self.hover is True: self.configure(cursor="pointinghand") self.canvas = tkinter.Canvas(master=self, highlightthicknes=0, background=self.bg_color, width=self.width, height=self.height) self.canvas.place(x=0, y=0) if self.hover is True: self.canvas.bind("", self.on_enter) self.canvas.bind("", self.on_leave) self.canvas.bind("", self.clicked) self.canvas.bind("", self.clicked) self.canvas_fg_parts = [] self.canvas_border_parts = [] self.text_label = None self.image_label = None # no image given if self.image is None: # create tkinter.Label with text self.text_label = tkinter.Label(master=self, font=self.text_font, bg=self.fg_color, fg=self.text_color) self.text_label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # bind events the the button click and hover events also to the text_label if self.hover is True: self.text_label.bind("", self.on_enter) self.text_label.bind("", self.on_leave) self.text_label.bind("", self.clicked) self.text_label.bind("", self.clicked) self.set_text(self.text) # use the given image else: # create tkinter.Label with image on it self.image_label = tkinter.Label(master=self, image=self.image, bg=self.fg_color) self.image_label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # bind events the the button click and hover events also to the image_label if self.hover is True: self.image_label.bind("", self.on_enter) self.image_label.bind("", self.on_leave) self.image_label.bind("", self.clicked) self.image_label.bind("", self.clicked) self.draw() def draw(self): self.canvas.delete("all") self.canvas_fg_parts = [] self.canvas_border_parts = [] self.canvas.configure(bg=self.bg_color) # border button parts if self.border_width > 0: if self.corner_radius > 0: self.canvas_border_parts.append(self.canvas.create_oval(0, 0, self.corner_radius * 2, self.corner_radius * 2)) self.canvas_border_parts.append(self.canvas.create_oval(self.width - self.corner_radius * 2, 0, self.width, self.corner_radius * 2)) self.canvas_border_parts.append(self.canvas.create_oval(0, self.height - self.corner_radius * 2, self.corner_radius * 2, self.height)) self.canvas_border_parts.append(self.canvas.create_oval(self.width - self.corner_radius * 2, self.height - self.corner_radius * 2, self.width, self.height)) self.canvas_border_parts.append(self.canvas.create_rectangle(0, self.corner_radius, self.width, self.height - self.corner_radius)) self.canvas_border_parts.append(self.canvas.create_rectangle(self.corner_radius, 0, self.width - self.corner_radius, self.height)) # inner button parts if self.corner_radius > 0: self.canvas_fg_parts.append(self.canvas.create_oval(self.border_width, self.border_width, self.border_width + self.inner_corner_radius * 2, self.border_width + self.inner_corner_radius * 2)) self.canvas_fg_parts.append(self.canvas.create_oval(self.width - self.border_width - self.inner_corner_radius * 2, self.border_width, self.width - self.border_width, self.border_width + self.inner_corner_radius * 2)) self.canvas_fg_parts.append(self.canvas.create_oval(self.border_width, self.height - self.border_width - self.inner_corner_radius * 2, self.border_width + self.inner_corner_radius * 2, self.height-self.border_width)) self.canvas_fg_parts.append(self.canvas.create_oval(self.width - self.border_width - self.inner_corner_radius * 2, self.height - self.border_width - self.inner_corner_radius * 2, self.width - self.border_width, self.height - self.border_width)) self.canvas_fg_parts.append(self.canvas.create_rectangle(self.border_width + self.inner_corner_radius, self.border_width, self.width - self.border_width - self.inner_corner_radius, self.height - self.border_width)) self.canvas_fg_parts.append(self.canvas.create_rectangle(self.border_width, self.border_width + self.inner_corner_radius, self.width - self.border_width, self.height - self.inner_corner_radius - self.border_width)) for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.fg_color, width=0) for part in self.canvas_border_parts: self.canvas.itemconfig(part, fill=self.border_color, width=0) def configure_color(self, bg_color=None, fg_color=None, hover_color=None, text_color=None): if bg_color is not None: self.bg_color = bg_color else: self.bg_color = self.master.cget("bg") if fg_color is not None: self.fg_color = fg_color # change background color of image_label if self.image is not None: self.image_label.configure(bg=self.fg_color) if self.text_label is not None: self.text_label.configure(bg=self.fg_color) if hover_color is not None: self.hover_color = hover_color if text_color is not None: self.text_color = text_color if self.text_label is not None: self.text_label.configure(fg=self.text_color) self.draw() def set_text(self, text): if self.text_label is not None: self.text_label.configure(text=text, width=len(text)) def on_enter(self, event=0): for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.hover_color, width=0) if self.text_label is not None: # change background color of image_label self.text_label.configure(bg=self.hover_color) if self.image_label is not None: # change background color of image_label self.image_label.configure(bg=self.hover_color) def on_leave(self, event=0): for part in self.canvas_fg_parts: self.canvas.itemconfig(part, fill=self.fg_color, width=0) if self.text_label is not None: # change background color of image_label self.text_label.configure(bg=self.fg_color) if self.image_label is not None: # change background color of image_label self.image_label.configure(bg=self.fg_color) def clicked(self, event=0): if self.function is not None: self.function() self.on_leave() ================================================ FILE: tuner_ui_parts/tkinter_custom_button_imageset.py ================================================ import tkinter import sys class TkinterCustomButtonImageset(tkinter.Frame): """ tkinter custom button with image, takes a image_dict with images like the following: image_dict = {"standard": ImageTk.PhotoImage, "clicked": ImageTk.PhotoImage, "standard_hover": ImageTk.PhotoImage, "clicked_hover": ImageTk.PhotoImage} """ def __init__(self, image_dict=None, hover=True, bg_color="black", command=None, *args, **kwargs): super().__init__(*args, **kwargs) self.image_dict = image_dict self.pressed = False self.bg_color = bg_color self.function = command self.hover = hover self.configure(bg=self.bg_color) self.label = tkinter.Label(master=self, image=image_dict["standard"], bg=self.bg_color) self.label.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) if sys.platform == "darwin" and self.hover is True: self.configure(cursor="pointinghand") if self.hover is True: self.bind("", self.on_enter) self.bind("", self.on_leave) self.bind("", self.clicked) self.label.bind("", self.clicked) def configure_color(self, bg_color=None): if bg_color is not None: self.bg_color = bg_color self.label.configure(bg=self.bg_color) def on_enter(self, event): if self.pressed is False: self.label.configure(image=self.image_dict["standard_hover"]) if self.pressed: self.label.configure(image=self.image_dict["clicked_hover"]) def on_leave(self, enter): if self.pressed is False: self.label.configure(image=self.image_dict["standard"]) if self.pressed: self.label.configure(image=self.image_dict["clicked"]) def clicked(self, event): if self.pressed is False: self.pressed = True self.label.configure(image=self.image_dict["clicked"]) else: self.pressed = False self.label.configure(image=self.image_dict["standard"]) if self.function: self.function() def is_pressed(self): return self.pressed def set_pressed(self, pressed): if pressed is True: self.pressed = True self.label.configure(image=self.image_dict["clicked"]) else: self.pressed = False self.label.configure(image=self.image_dict["standard"]) ================================================ FILE: usage_monitoring/__init__.py ================================================ ================================================ FILE: usage_monitoring/usage_monitor.py ================================================ import smtplib import sys import json import threading from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText try: from usage_monitoring.usage_monitor_credentials import UsageMonitorCredentials as Credentials except ImportError: Credentials = None class UsageMonitor: """ Simple class to send log information from python via mail. The mails are send and received by the same address, so only on mail address is needed. """ @classmethod def send_msg(cls, subject, msg_dict): try: if Credentials is not None: with smtplib.SMTP(Credentials.get("server"), Credentials.get("port")) as server: server.starttls() server.login(Credentials.get("mail"), Credentials.get("token")) msg = MIMEMultipart() msg['From'] = Credentials.get("mail") msg['To'] = Credentials.get("mail") msg['Subject'] = subject msg.attach(MIMEText(json.dumps(msg_dict, indent=4), 'plain')) server.send_message(msg) except Exception as err: # sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(err).__name__, err)) pass @classmethod def new_log_msg_thread(cls, open_times, user_id): # only the random user id (10 digits) and the open_times are send msg_dict = {"user_id": user_id, "opening_times": open_times} cls.send_msg("GuitarTuner-LOG", msg_dict) @classmethod def new_log_msg(cls, open_times, user_id): try: new_thread = threading.Thread(daemon=True, target=cls.new_log_msg_thread, args=(open_times, user_id)) new_thread.start() except Exception as err: # sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(err).__name__, err)) pass