In my new program, I kept having the same lines of code show up, so I decided to make a function, and call it when I want. But I keep getting an error that tells me "my function in not defined". I am new to Python programming and I can't figure it out!
This is my code:
import tkinter as tk
from tkinter import ttk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
#Window_Creation
scr_xloc = int(self.winfo_screenwidth() / 2 - 800 / 2)
scr_yloc = int(self.winfo_screenheight() / 2 - 600 / 2 - 30)
self.geometry("800x600+{}+{}".format(scr_xloc, scr_yloc))
self.minsize(width = 800, height = 600)
...
def Factorial_Calculation():
user_input = int(float(user_input))
import math
factorial_num = math.factorial(user_input)
self.Output_Box.delete("1.0", "end")
self.Output_Box.insert("1.0", str(user_input) + "! = " + str(factorial_num))
def x_Factorial_Loop(self, event):
global user_input
...
Factorial_Calculation()
Your problem is the calling of Factorial_Calculation(), you should call it within the class as self.Factorial_Calculation() but outside of the class is a different thing. Add "self." in front of your called function, as it applies to that class you called it in and pulls up the definition from the class you called it in.
Related
I am a new pyqtgraph users,try to "Embedding widgets inside PyQt applications"following the instructions in http://www.pyqtgraph.org/documentation/how_to_use.html. in my example I promote Graphics view to PlotWidget, then save as "test2.ui", also follow the "crosshair/mouse interaction" example,my code:
import sys
import numpy
from PyQt5 import QtCore, QtGui,uic,QtWidgets
from PyQt5.QtWidgets import *
import pyqtgraph as pg
import os
hw,QtBaseClass=uic.loadUiType("test.ui")
def gaussian(A, B, x):
return A * numpy.exp(-(x / (2. * B)) ** 2.)
class MyApp(QtWidgets.QMainWindow, hw):
def __init__(self):
super().__init__()
self.setupUi(self)
winSize=self.size()
self.view.resize(winSize.width(),winSize.height())
x = numpy.linspace(-5., 5., 10000)
y =gaussian(5.,0.2, x)
self.p=self.view.plot(x,y)
proxy = pg.SignalProxy(self.view.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
self.view.enableAutoRange("xy", True)
def mouseMoved(evt):
print("mouseTest")
mousePoint = self.p.vb.mapSceneToView(evt[0])
label.setText(
"<span style='font-size: 14pt; color: white'> x = %0.2f, <span style='color: white'> y = %0.2f</span>" % (
mousePoint.x(), mousePoint.y()))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
it seems not get the mouse move event;
after change
proxy = pg.SignalProxy(self.view.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
to
self.view.scene().sigMouseMoved.connect(self.mouseMoved),
output"MouseTest",but program imediatly crash.
can any one give me some help
Two things:
Re: Crashing
It seems as if you haven't placed a label in the GUI to modify, perhaps your code is seeing this and kicks it back to you. If you're using qtDesigner, it is likely defined as self.label, and in my GUI, I was required to use self.label to reference it.
Re: mouseMoved function
I was just struggling with a similar issue of it not working. I was able to get mine to work by changing the evt[0] to simply evt, something I think they moved to from pyqt4 to pyqt5.
Here's an example of what I was able to get to work:
..........setup code above... IN THE setupUi function:
..........setup code above...
Plotted = self.plot
vLine = pg.InfiniteLine(angle=90, movable=False)
hLine = pg.InfiniteLine(angle=0, movable=False)
Plotted.addItem(vLine, ignoreBounds=True)
Plotted.addItem(hLine, ignoreBounds=True)
Plotted.setMouseTracking(True)
Plotted.scene().sigMouseMoved.connect(self.mouseMoved)
def mouseMoved(self,evt):
pos = evt
if self.plot.sceneBoundingRect().contains(pos):
mousePoint = self.plot.plotItem.vb.mapSceneToView(pos)
self.label.setText("<span style='font-size: 15pt'>X=%0.1f, <span style='color: black'>Y=%0.1f</span>" % (mousePoint.x(),mousePoint.y()))
self.plot.plotItem.vLine.setPos(mousePoint.x())
self.plot.plotItem.hLine.setPos(mousePoint.y()
...the if__name__ =="__main__": function .....
In my case, I did not pass the proxy statement, and instead just went for the sigMouseMoved since it already passes the information the proxy would. I think this was in the example in pyqt5 (and commented out) because it was the change. However, the comment didn't specifically state this.
I'm having trouble creating widgets in a Jupyter notebook that update when other widget values are changed. This is the code I've been playing around with:
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
from IPython.display import display
def func(arg1,arg2):
print arg1
print arg2
choice = widgets.ToggleButtons(description='Choice:',options=['A','B'])
display(choice)
metric = widgets.Dropdown(options=['mercury','venus','earth'],description='Planets:')
text = widgets.Text(description='Text:')
a = interactive(func,
arg1=metric,
arg2=text,
__manual=True)
def update(*args):
if choice.value == 'A':
metric = widgets.Dropdown(options=['mercury','venus','earth'],description='Planets:')
text = widgets.Text(description='Text:')
a.children = (metric,text)
else:
metric = widgets.Dropdown(options=['monday','tuesday','wednesday'],description='Days:')
text2 = widgets.Textarea(description='Text2:')
a.children = (metric,text2)
choice.observe(update,'value')
display(a)
The resulting widgets metric and text do change based whether A or B is selected, but the problem is that the "Run func" button goes away as soon as I change to B. I've tried adding the __manual attribute immediately before display(a), adding it within update, and several other places. How do I change the children of the widget box without overwriting the fact that I want to manually run the function?
I am learning Python and Tkinter on my own and I have some questions regarding this code that I am writing.
I am trying to get the program to execute two functions that are part of a class.
So when I try to execute the below code tkinter executes the first function but does not execute function 2 and I don't understand why.
Can someone please help me with this.
And in function2 the value of j needs to equal the value of j from function1.
Thank you.
from tkinter import *
myapp=Tk()
myapp.geometry('1100x700+100+50')
myapp.title('List Generator')
input1=IntVar()
input2=IntVar()
class Myclass:
def __init__(self):
text1=input1.get()
text2=input2.get()
ex1=float(text1)
ex2=float(text2)
totbtu=float(ex1*ex2)
realbtu=totbtu+(totbtu*0.15)
j= float(totbtu + 100)
Label(myapp, text=totbtu).place(x=600,y=20)
Label(myapp, text=realbtu).place(x=600,y=60)
Label(myapp, text=j).place(x=600,y=100)
def function2(self):
h=j+33
Label(myapp, text=h).place(x=600,y=140)
label1 = Label(myapp, text='Enter Area').place(x=10,y=10)
area_entry=Entry(myapp,textvariable=input1 ).place(x=140,y=10)
label11 = Label(myapp,text='SQ FT',).place(x=270,y=10)
label2 = Label(myapp, text='Enter Load').place(x=10,y=35)
area_entry=Entry(myapp,textvariable=input2 ).place(x=140,y=35)
label22 = Label(myapp,text="BTU's/SQ FT",).place(x=270,y=35)
button1 = Button(myapp, text = 'Generate',padx=5,pady=5,command=Myclass).place(x=10,y=70)
myapp.mainloop()
If I understand your question correctly, you need to call 2 functions with one button command and you also need to use one value in both functions (I'm assuming).
Take a look at my solution:
from Tkinter import *
myapp=Tk()
myapp.geometry('1100x700+100+50')
myapp.title('List Generator')
input1=IntVar()
input2=IntVar()
j = 0 #needed for the value to be referenced in both function1 and function2
def function1():
global j
text1=input1.get()
text2=input2.get()
ex1=float(text1)
ex2=float(text2)
totbtu=float(ex1*ex2)
realbtu=totbtu+(totbtu*0.15)
j= float(totbtu + 100)
Label(myapp, text=totbtu).place(x=600,y=20)
Label(myapp, text=realbtu).place(x=600,y=60)
Label(myapp, text=j).place(x=600,y=100)
print(j)
def function2():
global j
h=j+33
Label(myapp, text=h).place(x=600,y=140)
print(j)
def wombocombo():
function1()
function2()
label1 = Label(myapp, text='Enter Area').place(x=10,y=10)
area_entry=Entry(myapp,textvariable=input1 ).place(x=140,y=10)
label11 = Label(myapp,text='SQ FT',).place(x=270,y=10)
label2 = Label(myapp, text='Enter Load').place(x=10,y=35)
area_entry=Entry(myapp,textvariable=input2 ).place(x=140,y=35)
label22 = Label(myapp,text="BTU's/SQ FT",).place(x=270,y=35)
button1 = Button(myapp, text = 'Generate',padx=5,pady=5,command=wombocombo).place(x=10,y=70)
myapp.mainloop()
When you dictate a function to be called when a button is pressed, you use command=myFunction myFunction is a function, not a class. And as such, when a class like Myclass is the command instead of a function, problems will occur.
To execute 2 functions with 1 command, simply combine both functions into 1. If you take a look at the wombocombo function, it will call both function1 and function2, hitting 2 birds with 1 stone.
As for sharing a variable between both functions, I always find it easiest to go broader one step on the scope ladder and add my variable there.
In this example, we needed the same j variable in both function1 and function2. Going broader in scope, we define j in a place that both function1 and function2 can access.
I am currently writing a small game under separate files and am having an issue with pygame.sprite.Sprite. Every time I go to run the player class I get this error AttrbuteError: "module" object has no attribute "sprite". I have done many searches on this site and have also looked on the pygame website for answers but I have only found other bits of code and answers that do not resolve my current issue. If anyone could help me with my issue that would be great.
here's my class for the player:
import pygame
import pygame.sprite as Sprite
class player(Sprite.sprite):
def _init_(self,plyrmovement,plyrhealth,plyrdirection):
Sprite.Sprite._init_(self)
def plyrmovement(left,right):
position=[100,100]
direct_left = 'player left'
direct_right = 'player right'
def right():
if event.key == ord('d'):
position[0] += 5
plyrdirection = direct_right
sprite.sprite='playerleft'
def left():
if event.key == ord('a'):
position[0] -= 5
plyrdirection = direct_left
sprite.sprite = 'playerright'
def shoot(self,bullet):
if event.key == K_SPACE:
bullet.bulletmove
def plyrhealth(self):
self.health = 100
class bullet(pygame.Sprite.Sprite):
def _init_(self,bulletmove,bulletdamage):
pygame.image.load('bullet sprite.png')
The full name is pygame.sprite.Sprite.
If you use import pygame.sprite as Sprite then correct name is player(Sprite.Sprite) not player(Sprite.sprite) - see upper S in both Sprite.
As for me it is better to use class player(pygame.sprite.Sprite) and bullet(pygame.sprite.Sprite) - lower s in first sprite and upper S in second Sprite - and without import pygame.sprite as Sprite
import pygame
class Player(pygame.sprite.Sprite):
def __init__(self,plyrmovement, plyrhealth, plyrdirection):
pygame.sprite.Sprite.__init__(self)
# ...rest...
class Bullet(pygame.sprite.Sprite):
def __init__(self, bulletmove, bulletdamage):
pygame.sprite.Sprite.__init__(self)
# ...rest...
BTW:
it has to be two _ before and after init
you could use CamelCase names for classes - Player, Bullet - similar to Sprite, Rect. See suggestions in PEP8 (PEP 0008 -- Style Guide for Python Code)(PEP8 - Class Names)
use empty line before class and def to make code more readable (PEP8 - Blank Lines).
I am trying to find the simplest example of a custom widget being written for Gtk-3.
So far the best thing I've found is this (using PyGTK), but it seems to be targeted to Gtk-2.
BTW: I don't care the language it is written in, but if we can avoid C++, much better!
Python3 Gtk3 it is, then:
from gi.repository import Gtk
class SuperSimpleWidget(Gtk.Label):
__gtype_name__ = 'SuperSimpleWidget'
Here is a non-trivial example that actually does something, namely paints its background and draws a diagonal line through it. I'm inheriting from Gtk.Misc instead of Gtk.Widget to save some boilerplate (see below):
class SimpleWidget(Gtk.Misc):
__gtype_name__ = 'SimpleWidget'
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self.set_size_request(40, 40)
def do_draw(self, cr):
# paint background
bg_color = self.get_style_context().get_background_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*list(bg_color))
cr.paint()
# draw a diagonal line
allocation = self.get_allocation()
fg_color = self.get_style_context().get_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*list(fg_color));
cr.set_line_width(2)
cr.move_to(0, 0) # top left of the widget
cr.line_to(allocation.width, allocation.height)
cr.stroke()
Finally, if you really want to derive from Gtk.Widget then you also have to set up a drawing background. Gtk.Misc does that for you, but Gtk.Widget could be a container that doesn't actually draw anything itself. But inquiring minds want to know, so you could do it like so:
from gi.repository import Gdk
class ManualWidget(Gtk.Widget):
__gtype_name__ = 'ManualWidget'
def __init__(self, *args, **kwds):
# same as above
def do_draw(self, cr):
# same as above
def do_realize(self):
allocation = self.get_allocation()
attr = Gdk.WindowAttr()
attr.window_type = Gdk.WindowType.CHILD
attr.x = allocation.x
attr.y = allocation.y
attr.width = allocation.width
attr.height = allocation.height
attr.visual = self.get_visual()
attr.event_mask = self.get_events() | Gdk.EventMask.EXPOSURE_MASK
WAT = Gdk.WindowAttributesType
mask = WAT.X | WAT.Y | WAT.VISUAL
window = Gdk.Window(self.get_parent_window(), attr, mask);
self.set_window(window)
self.register_window(window)
self.set_realized(True)
window.set_background_pattern(None)
Edit and to actually use it:
w = Gtk.Window()
w.add(SimpleWidget())
w.show_all()
w.present()
import signal # enable Ctrl-C since there is no menu to quit
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
Or, more fun, use it directly from the ipython3 REPL:
from IPython.lib.inputhook import enable_gtk3
enable_gtk3()
w = Gtk.Window()
w.add(SimpleWidget())
w.show_all()
w.present()
Here's a tutorial about writing a GTK 3 custom container widget in C: http://ptomato.name/advanced-gtk-techniques/html/custom-container.html It's probably more complicated than you need for writing a simple widget. You might also check out the migration guide from GTK 2 to 3: https://developer.gnome.org/gtk3/stable/gtk-migrating-2-to-3.html
SO far the best reference to:
- understand Gobject (from wich gtk widget derive)
- have some boiler code and c code
https://developer.gnome.org/gobject/stable/howto-gobject.html
I know it's not Python written, but converting from c to python is a piece of cake
(what matter is the algorithm, not the language)