瞄准细节,方得始终
今觅得一码,见其——”作为参数的方法没有带括号也能运行”,诧异,整理若下
一、先演示没有括号的
设有方法
def move_turtle(self):
self.turtle.forward(50)
执行调用
self.move_btu.clicked.connect(self.move_turtle)
没有括号的时候,是告诉Python运行改方法时将 该方法本身作为参数,而不是其计算结果
二、带括号的
有括号的时候的,则返回括号内方法的计算结果。
distance_spin = QSpinBox()
distance_spin.setValue(20)
turtle.forward(distance_spin.value())
这里最后一句的调用就加了 小括号 ,所以最后应该是返回20,
截断代码不好理解放上完整代码
import turtle
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class TuControl(QWidget):
def __init__(self,turtle):
super(TuControl,self).__init__()
self.turtle = turtle
self.left_btu = QPushButton("Left",self)
self.right_btu = QPushButton("Right",self)
self.move_btu = QPushButton("Move",self)
self.distance_spin = QSpinBox()
self.controlsLayout = QGridLayout()
self.controlsLayout.addWidget(self.left_btu,0,0)
self.controlsLayout.addWidget(self.right_btu,0,1)
self.controlsLayout.addWidget(self.distance_spin ,1,0)
self.controlsLayout.addWidget(self.move_btu,1,1)
self.setLayout(self.controlsLayout)
self.distance_spin.setRange(0,100)
self.distance_spin.setSingleStep(5)
self.distance_spin.setValue(20)
self.move_btu.clicked.connect(self.move_turtle)
self.right_btu.clicked.connect(self.turn_turtle_right)
self.left_btu.clicked.connect(self.turn_turtle_left)
def turn_turtle_left(self):
self.turtle.left(45)
def turn_turtle_right(self):
self.turtle.right(45)
def move_turtle(self):
self.turtle.forward(self.distance_spin.value())
#set up
window = turtle.Screen()
bab = turtle.Turtle()
#Create a Qt application
app = QApplication(sys.argv)
control_window = TuControl(bab)
control_window.show()
#main loop
app.exec_()
sys.exit()